Search code examples
androidfindviewbyidbottom-sheet

findViewById() returns null - what should I do?


I am using a bottomSheetBehavior in my android project. See codes below:

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">
    .
    .
    .

The problem is this line:

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

is returning null. I even changed the code place to onResume, but it did not work. When I get another element in test_end_of_online_game_popup, it works well and not null.

What is the problem?

tnx


Solution

  • Two choices:

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

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