findViewById() returns null - 我该怎么办?

findViewById() returns null - what should I do?

我在 android 项目中使用 bottomSheetBehavior。请参阅以下代码:

onlineGame.java:

 // get the bottom sheet view
        ConstraintLayout llBottomSheet = findViewById(R.id.end_of_online_game_bottom_sheet_behavior_cl);

// init the bottom sheet behavior
        end_of_online_game_popup = BottomSheetBehavior.from(llBottomSheet);

avtivity_online_game.xml:

.
.
.

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.androidsample.BottomSheetActivity">

        <!-- include bottom sheet -->
        <include
            android:id="@+id/includeBottomSheetBehavior"
            layout="@layout/test_end_of_online_game_popup" />

    </android.support.design.widget.CoordinatorLayout>
.
.
.

test_end_of_online_game_popup.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/end_of_online_game_bottom_sheet_behavior_cl"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/cardview_light_background"
    android:visibility="gone"
    app:behavior_hideable="false"
    app:behavior_peekHeight="120dp"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
    .
    .
    .

问题出在这一行:

ConstraintLayout llBottomSheet = findViewById(R.id.end_of_online_game_bottom_sheet_behavior_cl);

正在返回 null。我什至将代码位置更改为onResume,但它没有用。当我在 test_end_of_online_game_popup 中获得另一个元素时,它运行良好并且不为空。

有什么问题?

tnx

因为您正在使用包含的布局:

在您为包含标签提供的 ID 上使用查找视图

findViewById(R.id.includeBottomSheetBehavior)

或者您可以省略布局标记中的 id,这样它就不会被覆盖。

标签中,只需要layout属性。此属性是对您希望包含的布局文件的引用。此标记还允许您覆盖包含的布局的一些属性。

上面的例子表明你可以使用android:id来指定包含布局的根视图的id; 如果定义了布局,它也会覆盖包含的布局的 ID。同样,您可以覆盖所有布局参数。

来源:http://www.curious-creature.com/2009/02/25/android-layout-trick-2-include-to-reuse/

两个选择:

  1. ConstraintLayout llBottomSheet = findViewById(R.id. includeBottomSheetBehavior);

  2. <include layout="@layout/test_end_of_online_game_popup" />

试试这个:

View view = findViewById(R.id.includeBottomSheetBehavior);//firstly get the root view ID
ConstraintLayout llBottomSheet = view.findViewById(R.id.end_of_online_game_bottom_sheet_behavior_cl);