242

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.

John Doe
  • 397
  • 3
  • 18
Michal Dymel
  • 4,312
  • 3
  • 23
  • 32

15 Answers15

425

I'm not sure I have followed your question- are you trying to attach a child view to the RelativeLayout? If so you want to do something along the lines of:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);
loeschg
  • 29,961
  • 26
  • 97
  • 150
Graeme Duncan
  • 8,166
  • 2
  • 20
  • 13
  • 3
    I get an error: 02-25 22:21:19.324: ERROR/AndroidRuntime(865): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. – Michal Dymel Feb 25 '10 at 21:24
  • @MichalDymel: you probably are inflating same xml agian. should inflate another. – Adil Soomro Nov 04 '11 at 10:35
  • 27
    Just tried this now, I needed: View child = getLayoutInflater().inflate(R.layout.child,null); – James May 24 '12 at 00:23
  • 3
    The problem isn't the code. It's fairly easy to follow code. Where do you make the xml file. is the type a theme style resource? the problem i think people me included is where are we placing this xml file – Lpc_dark Dec 24 '12 at 01:05
  • 17
    This isn't perfect. The 3-param version of the inflater should be used - here is why: http://www.doubleencore.com/2013/05/layout-inflation-as-intended/ – Nick Cardoso Apr 14 '14 at 15:00
  • 1
    Note: 3-param version does NOT have to be used for AlertDialog and PopupWindow. You can supply 'null' as the ViewGroup parameter for these. – IgorGanapolsky Apr 18 '14 at 17:20
  • 3
    The answer is incorrect, even if it works. Please check out this post https://possiblemobile.com/2013/05/layout-inflation-as-intended/ – ARK Oct 19 '15 at 19:28
  • @akshayrajkore your answer should be get more thumb ups, now i know why when i inflate a layout, the attributes being ignored, thanks bro – HendraWD Nov 30 '15 at 03:34
  • Current *Layout Inflation as Intended* link: https://wiresareobsolete.com/2013/05/layout-inflation-as-intended/ – Nolan Amy May 25 '21 at 20:49
113

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);
ccheneson
  • 49,072
  • 8
  • 63
  • 68
  • 4
    I have my main view inflated. The problem is I want to inflate part of it from other XML file. This item RelativeLayout is part of bigger layout and I want to fill it with layout from another XML file. – Michal Dymel Feb 25 '10 at 16:58
  • hum I m sorry then I have no clue :( . Are you using something like in your main view to include other layout? – ccheneson Feb 25 '10 at 17:13
  • No, it's simple layout. I think I will just add my elements programatically - without XML. Thanks for help! – Michal Dymel Feb 25 '10 at 21:25
28

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.

Jacksonkr
  • 31,583
  • 39
  • 180
  • 284
Shaista Naaz
  • 8,281
  • 9
  • 37
  • 50
  • (even later still) I am having difficulty implementing your answer. I tried the code you mentioned above but replaced 'item' with: 'R.layout.activity_layout' I'm getting an "There is no applicable method to '(int,int)'" could I trouble you for your thoughts? – Kyle Oct 31 '12 at 21:46
  • 1
    @Kyle - even later still. You cant use `R` resources as references to an object, they are just `int`s. You have to use `findViewById` passing it the `R` resource, then type cast it to your desired object. Then you can use it in function calls like `inflate`. (ie. `ViewGroup item = (ViewGroup) findViewById(R.layout.activity_layout);`... then you can use `item` like above.) – Pimp Trizkit Jan 27 '13 at 05:56
  • I guess I ment to use `RelativeLayout` instead of `ViewGroup` there in my example above, as you cant instantiate the base class `ViewGroup`. 5 minute edit rule got me. lol – Pimp Trizkit Jan 27 '13 at 06:05
  • Is it possible to hide parent and display only child view – NovusMobile Jul 04 '13 at 05:13
  • Thanks, this method helped out where I couldn't use the getContext() in the previous example since I am using fragments. – RightHandedMonkey Sep 05 '13 at 19:51
  • Glad it helped someone :-) – Shaista Naaz Sep 06 '13 at 07:33
  • @ShaistaNaaz Hi..I have created multiple view of same type..by inflate them ..i got a problem how am i supposed to get the each item resource id. – Janmejoy Aug 10 '15 at 16:32
  • I inflated some view (`ImageView`) and set it as action view - `menuItem.setActionView(view);` - `menuItem` is parent here? – user25 Mar 24 '18 at 16:06
20

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.

Maximus
  • 8,351
  • 3
  • 29
  • 37
  • Finally, thank you :) This allows to add multiple views to a single parent, but without the need to worry about the LayoutParams - which are read from the XML. Good job! – Sabo Sep 14 '13 at 20:57
14

Even simpler way is to use

View child = View.inflate(context, R.layout.child, null)
item.addChild(child) //attach to your item
Ashish Rawat
  • 3,363
  • 5
  • 29
  • 35
  • Using `View.inflate()`is the best way, no unnecessary `LayoutInflater` or `getSystemService(Context.LAYOUT_INFLATER_SERVICE)` or any of all that nuisance! :D – varun Jun 28 '19 at 16:17
11

Try this code :

  1. If you just want to inflate your layout :

View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,null); // Code for inflating xml layout
RelativeLayout item = view.findViewById(R.id.item);   
  1. If you want to inflate your layout in container(parent layout) :

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

layout inflation

View view = null;
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);
main.addView(view);
Attaullah
  • 3,856
  • 3
  • 48
  • 63
Happy Singh
  • 376
  • 3
  • 8
6

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)

Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
6

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.!

eSparkBiz Team
  • 110
  • 1
  • 5
4

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.

Asad AndyDev
  • 481
  • 5
  • 23
John smith
  • 1,781
  • 17
  • 27
3

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);
Kasim Rangwala
  • 1,765
  • 2
  • 23
  • 44
2

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();
Azurespot
  • 3,066
  • 3
  • 45
  • 73
2

With Kotlin, you can use:

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

[your_main_layout].apply {
    //..
    addView(content)
}
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
2

When add a layout to an Activity in Kotlin, see these steps:

  1. Add just in Activity - One layout as a parent

  2. Xml file of new

  3. Layout Give the value of R.

    val parent: LinearLayout =findViewById(R.id.stars)

    val view =
        LayoutInflater.from(applicationContext).inflate(R.layout.another, parent,false)
    

Where parent is not necessary, can be null But warning message will be appear

view.findViewById<ImageView>(R.id.ivTimer).setImageResource(R.drawable.t2)

Any view must be set value in this way, finally add

parent.apply {  addView(view)}
Mori
  • 2,653
  • 18
  • 24
-2

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);
SFDCCoder
  • 23
  • 4