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 activity
View otherLayout = LayoutInflater.from(this).inflate(R.layout.other,null);

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

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

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

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

//For example, adding a listener to the new layout
otherLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(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:


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