findViewById() returns null on included layout?

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?

Upvotes: 5

Views: 1731

Answers (4)

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

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.

Upvotes: 3

Khemraj Sharma
Khemraj Sharma

Reputation: 59004

Included layouts are added to your view already. You can do this way also.

findViewById(R.id.info_btn)
    .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
});

Upvotes: 0

Daniel RL
Daniel RL

Reputation: 353

You just need to do this:

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

Upvotes: 0

Fran Dioniz
Fran Dioniz

Reputation: 1314

If you have an included layout in your activity, you can access to the Button like if the button was inside the activity.

You only need to do:

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

Upvotes: 0

Related Questions