Skip to content Skip to sidebar Skip to footer

Findviewbyid() Returns Null For An Inflated Layout

I have an Activity and its layout. Now I need to add a LinearLayout from another layout, menu_layout.xml. LayoutInflater inflater; inflater = (LayoutInflater) this.getSystemService

Solution 1:

Explanation

When you inflate a layout, the layout is not in the UI yet, meaning the user will not be able to see it until it's been added. To do this, you must get a hold of a ViewGroup (LinearLayout,RelativeLayout,etc) and add the inflated View to it. Once they're added, you can work on them as you would with any other views including the findViewById method, adding listeners, changing properties, etc

Code

//Inside onCreate for example
setContentView(R.layout.main); //Sets the content of your activityViewotherLayout= LayoutInflater.from(this).inflate(R.layout.other,null);

//You can access them here, before adding `otherLayout` to your activityTextViewexample= (TextView) otherLayout.findViewById(R.id.exampleTextView);

//This container needs to be inside main.xmlLinearLayoutcontainer= (LinearLayout)findViewById(R.id.container);

//Add the inflated view to the container    
container.addView(otherLayout);

//Or access them once they're addedTextViewexample2= (TextView) findViewById(R.id.exampleTextView);

//For example, adding a listener to the new layout
otherLayout.setOnClickListener(newView.OnClickListener() {
    @OverridepublicvoidonClick(View view) {
        //Your thing
    }
});

Assuming

  • main.xml contains a LinearLayout with the id container
  • other.xml is a layout file in your project
  • other.xml contains a TextView with the id exampleTextView

Solution 2:

Try using

 layoutObject.findViewById();

Post a Comment for "Findviewbyid() Returns Null For An Inflated Layout"