Search code examples
androidandroid-linearlayout

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(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.menu_layout, null); 

After this, findViewById() returns null. Is there is any solution for that?

Note: I can't put both XML in one place, and using <include> also is not working.


Solution

  • 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