5

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?

4 Answers4

3

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.

Jeffrey Blattman
  • 22,176
  • 9
  • 79
  • 134
0

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
        }
});
Fran Dioniz
  • 1,134
  • 9
  • 12
0

You just need to do this:

findViewById(R.id.info_btn)
    .setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v)
{
    //Do things
}
});
Daniel RL
  • 353
  • 1
  • 12
0

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) {

        }
});
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212