Search code examples
androidxmlandroid-layoutandroid-fragmentslayout-inflater

Inflate an XML in Fragment programmatically


I have MainActivity.java as my first Fragment and the another Fragment being Fragment.java having a TabHost in it. When user clicks on a button in MainActivity, I want to inflate an XML in second fragment's Tab1.

OnClickListener of the Button in MainActivity is as follows:

btOkButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {

        LayoutInflater lf = getLayoutInflater();
        Fragment.updateTab1(lf);                
    }               
});

And updateTab1(..) method in Fragment class is:

public static void updateTab1(LayoutInflater lf) {
        lf.inflate(R.layout.xml_to_inflate, (ViewGroup)llTab1, false);
    }

Where:

llTab1 = (LinearLayout)getActivity().findViewById(R.id.tab1);

I am not getting any Exception while doing this, nor Force Close.

In Debug I can see all of this code run without any exception but no required XML being inflated.


Solution

  • Finally what worked for me:

    As working with fragments I had missed following line in onCreate() to make the inflater object work:

    inflater = getActivity().getLayoutInflater();

    and keeping the rest of code as it is.