Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findViewById() returns null on included layout?

Tags:

java

android

I have an included layout in my activity's XML layout like so:

<include
    layout="@layout/info_button"
    android:id="@+id/config_from_template_info_btn"/>

I'm trying to set an OnClickListener for the button inside of that included layout by doing this:

findViewById(R.id.config_from_template_info_btn)
        .findViewById(R.id.info_btn)
        .setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        //Do things
    }
});

However, this crashes on runtime with:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

The info_btn.xml layout simply contains Button widget like so:

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/info_btn"
        ...
        />
</merge>

What am I doing wrong here?

like image 373
You'reAGitForNotUsingGit Avatar asked Oct 17 '22 18:10

You'reAGitForNotUsingGit


1 Answers

The <merge.../> tag is removing the outer layout, which is the one with that ID. That's the purpose of merge: to collapse unnecessary layouts for better performance. Yours is one common case. You need a top-level XML container to hold the included views, but you don't actually need view layout functionality.

Either just use one find on info_btn, or don't use merge. The only reason you'd need to do the double find is if you were including multiple layouts that each had views with an ID of info_btn.

like image 189
Jeffrey Blattman Avatar answered Oct 21 '22 07:10

Jeffrey Blattman