[android] How to inflate one view with a layout

I have a layout defined in XML. It contains also:

<RelativeLayout
    android:id="@+id/item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

I would like to inflate this RelativeView with other XML layout file. I may use different layouts depending on a situation. How should I do it? I was trying different variations of

RelativeLayout item = (RelativeLayout) findViewById(R.id.item);
item.inflate(...)

But none of them worked fine.

The answer is


Even simpler way is to use

View child = View.inflate(context, R.layout.child, null)
item.addChild(child) //attach to your item

It's helpful to add to this, even though it's an old post, that if the child view that is being inflated from xml is to be added to a viewgroup layout, you need to call inflate with a clue of what type of viewgroup it is going to be added to. Like:

View child = getLayoutInflater().inflate(R.layout.child, item, false);

The inflate method is quite overloaded and describes this part of the usage in the docs. I had a problem where a single view inflated from xml wasn't aligning in the parent properly until I made this type of change.


If you want to add a single view multiple time then you have to use

   layoutInflaterForButton = getActivity().getLayoutInflater();

 for (int noOfButton = 0; noOfButton < 5; noOfButton++) {
        FrameLayout btnView = (FrameLayout) layoutInflaterForButton.inflate(R.layout.poll_button, null);
        btnContainer.addView(btnView);
    }

If you do like

   layoutInflaterForButton = getActivity().getLayoutInflater();
    FrameLayout btnView = (FrameLayout) layoutInflaterForButton.inflate(R.layout.poll_button, null);

and

for (int noOfButton = 0; noOfButton < 5; noOfButton++) {
            btnContainer.addView(btnView);
        }

then it will throw exception of all ready added view.


You inflate an XML resource. See the LayoutInflater doc .

If your layout is in a mylayout.xml, you would do something like:

View view; 
LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);

RelativeLayout item = (RelativeLayout) view.findViewById(R.id.item);

Though late answer, but would like to add that one way to get this

LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.mylayout, item );

where item is the parent layout where you want to add a child layout.


AttachToRoot Set to True

Just think we specified a button in an XML layout file with its layout width and layout height set to match_parent.

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/custom_button">
</Button>

On This Buttons Click Event We Can Set Following Code to Inflate Layout on This Activity.

LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.yourlayoutname, this);

Hope this solution works for you.!


With Kotlin, you can use:

val content = LayoutInflater.from(context).inflate(R.layout.[custom_layout_name], null)

[your_main_layout].apply {
    //..
    addView(content)
}

layout inflation

View view = null;
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);
main.addView(view);

I had the hardest time with this error, because of my unique circumstances, but finally found a solution.

My situation: I am using a separate view (XML) which holds a WebView, then opens in an AlertDialog when I click a button in my main activity view. But somehow or another the WebView belonged to the main activity view (probably because I pull the resource from here), so right before I assigned it to my AlertDialog (as a view), I had to get the parent of my WebView, put it into a ViewGroup, then remove all the views on that ViewGroup. This worked, and my error went away.

// set up Alert Dialog box
AlertDialog.Builder alert = new AlertDialog.Builder(this);
// inflate other xml where WebView is
LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.your_webview_layout, null);
final WebView webView = (WebView) v.findViewById(R.id.your_webview_id);

// more code...

.... later on after I loaded my WebView ....

// first, remove the parent of WebView from it's old parent so can be assigned a new one.
ViewGroup vg = (ViewGroup) webView.getParent();
vg.removeAllViews();

// put WebView in Dialog box
alert.setView(webView);
alert.show();

Try this code :

  1. If you just want to inflate your layout :

_x000D_
_x000D_
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,null); // Code for inflating xml layout_x000D_
RelativeLayout item = view.findViewById(R.id.item);   
_x000D_
_x000D_
_x000D_

  1. If you want to inflate your layout in container(parent layout) :

_x000D_
_x000D_
LinearLayout parent = findViewById(R.id.container);        //parent layout._x000D_
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,parent,false); _x000D_
RelativeLayout item = view.findViewById(R.id.item);       //initialize layout & By this you can also perform any event._x000D_
parent.addView(view);             //adding your inflated layout in parent layout.
_x000D_
_x000D_
_x000D_


If you're not in an activity you can use the static from() method from the LayoutInflater class to get a LayoutInflater, or request the service from the context method getSystemService() too :

LayoutInflater i;
Context x;       //Assuming here that x is a valid context, not null

i = (LayoutInflater) x.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//OR
i = LayoutInflater.from(x);

(I know it's almost 4 years ago but still worth mentioning)


If you are you trying to attach a child view to the RelativeLayout? you can do by following

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, item, true);

I had used below snippet of code for this and it worked for me.

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
linearLayout.addView(child);

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to layout-inflater

onCreateOptionsMenu inside Fragments How does the getView() method work when creating your own custom adapter? Call to getLayoutInflater() in places not in activity How to change the Text color of Menu item in Android? What does LayoutInflater in Android do? How to change the background color of the options menu? How to inflate one view with a layout

Examples related to android-inflate

What does it mean to inflate a view from an xml file? android.view.InflateException: Binary XML file line #12: Error inflating class <unknown> What does LayoutInflater in Android do? How to inflate one view with a layout