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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With