Inflate layout programmatically within another layout

AndroidXmlAndroid LayoutAndroid Inflate

Android Problem Overview


I need help with my android app. I need inflate a layout within another layout and I dont know how I do. My xml code is this:

  • item.xml - I need inflate multiple xml (depending on a variable number)

          <RelativeLayout
               android:id="@+id/cartel_N1"
               android:layout_width="150dp"
               android:layout_height="match_parent"
               android:background="@color/tabhost_background_pressed"
               android:layout_marginRight="22dp"
               android:orientation="vertical" >
          
          <ImageView 
              android:id="@+id/img_N1"
              android:layout_width="120dp"
              android:layout_height="120dp"
              android:layout_marginLeft="15dp"
              android:layout_marginTop="15dp"
              android:layout_marginRight="15dp"
              android:src="@drawable/mcdonalds_icon" />
          
          <TextView 
              android:id="@+id/title_N1"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:gravity="center_horizontal"
              android:text="McDonals del CC Alcampo"
              android:layout_marginBottom="10dp"
              android:layout_marginLeft="15dp"
              android:layout_marginRight="15dp"
              android:textSize="15sp" />
          
          <TextView 
              android:id="@+id/categoria_N1"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:gravity="center_horizontal"
              android:text="CATEGORIA"
              android:textSize="16sp"
              android:textStyle="bold"
              android:layout_marginLeft="15dp"
              android:layout_marginRight="15dp" />
          
          <RelativeLayout 
              android:id="@+id/stars_and_distance_N1"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal" >
    
              <ImageView
              	android:id="@+id/stars_N1"
                  android:layout_width="wrap_content"
      	        android:layout_height="wrap_content"
      	        android:src="@drawable/stars_25"
      	        android:layout_marginLeft="15dp"
      	        android:layout_marginTop="7dp" />
              
               
              <TextView
                  android:id="@+id/distance_N1"
                  android:layout_width="wrap_content"
      	        android:layout_height="wrap_content"
      	        android:text="200m"
      	        android:textSize="12sp"
      	        android:layout_alignParentRight="true"
      	        android:layout_marginRight="15dp"
      	        android:gravity="center_vertical"
      	        android:layout_marginTop="3dp" />
              
              
              <ImageView
                  android:id="@+id/icon_pos_N1"
                  android:layout_width="10dp"
      	        android:layout_height="10dp"
      	        android:src="@drawable/marker_distance"
      	        android:layout_toLeftOf="@id/distance_N1"
      	        android:layout_marginTop="7dp" />
              
          </RelativeLayout><LinearLayout
          android:id="@+id/cartel_N1"
          android:layout_width="150dp"
          android:layout_height="match_parent"
          android:background="@color/tabhost_background_pressed"
          android:layout_marginRight="22dp"
          android:orientation="vertical" >
          
          <ImageView 
              android:id="@+id/img_N1"
              android:layout_width="120dp"
              android:layout_height="120dp"
              android:layout_marginLeft="15dp"
              android:layout_marginTop="15dp"
              android:layout_marginRight="15dp"
              android:src="@drawable/mcdonalds_icon" />
          
          <TextView 
              android:id="@+id/title_N1"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:gravity="center_horizontal"
              android:text="McDonals del CC Alcampo"
              android:layout_marginBottom="10dp"
              android:layout_marginLeft="15dp"
              android:layout_marginRight="15dp"
              android:textSize="15sp" />
          
          <TextView 
              android:id="@+id/categoria_N1"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:gravity="center_horizontal"
              android:text="CATEGORIA"
              android:textSize="16sp"
              android:textStyle="bold"
              android:layout_marginLeft="15dp"
              android:layout_marginRight="15dp" />
          
          <RelativeLayout 
              android:id="@+id/stars_and_distance_N1"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal" >
    
              <ImageView
              	android:id="@+id/stars_N1"
                  android:layout_width="wrap_content"
      	        android:layout_height="wrap_content"
      	        android:src="@drawable/stars_25"
      	        android:layout_marginLeft="15dp"
      	        android:layout_marginTop="7dp" />
              
               
              <TextView
                  android:id="@+id/distance_N1"
                  android:layout_width="wrap_content"
      	        android:layout_height="wrap_content"
      	        android:text="200m"
      	        android:textSize="12sp"
      	        android:layout_alignParentRight="true"
      	        android:layout_marginRight="15dp"
      	        android:gravity="center_vertical"
      	        android:layout_marginTop="3dp" />
              
              
              <ImageView
                  android:id="@+id/icon_pos_N1"
                  android:layout_width="10dp"
      	        android:layout_height="10dp"
      	        android:src="@drawable/marker_distance"
      	        android:layout_toLeftOf="@id/distance_N1"
      	        android:layout_marginTop="7dp" />
              
          </RelativeLayout>
    
  • This is my main xml:

      <ScrollView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
        <LinearLayout
             android:id="@+id/container_destacado"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:orientation="vertical" >
                 
                 <!-- Inflate multiple xml file here -->
    
            </LinearLayout>
      </ScrollView>
    

Android Solutions


Solution 1 - Android

You could use something like

LayoutInflater inflater = LayoutInflater.from(context);

//to get the MainLayout
View view = inflater.inflate(container_destacado, null);
...
//Avoid pass null in the root it ignores spaces in the child layout

View inflatedLayout= inflater.inflate(R.layout.yourLayout, (ViewGroup) view, false);
containerDestacado.addView(inflatedLayout);

Solution 2 - Android

You can implement this like below:

LayoutInflater linf;
LinearLayout rr;

linf = (LayoutInflater) getApplicationContext().getSystemService(
		Context.LAYOUT_INFLATER_SERVICE);
linf = LayoutInflater.from(activity.this);

rr = (LinearLayout) findViewById(R.id.container_destacado);

for (int i = 1; i < NoOfTimes; i++) {

    final View v = linf.inflate(R.layout.item, null);
    rr.addView(v);
}

Solution 3 - Android

ll = (LinearLayout) findViewById(R.id.container_destacado);  // ll is the layout where your inflated layout will be added 
linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int pos = 0;
	while (pos < noOfTimes) 
	{
		View myView = linflater.inflate(R.layout.item, null); //here item is the the layout you want to inflate 
		myView.setId(pos);
		/*
           You can change TextView text and ImageView images here e.g.
           TextView tv = (TextView)myView.findViewById(R.id.title_N1);
           tv.setText(pos);

        */
		pos++;
		ll.addView(myView);
	}

Solution 4 - Android

In some point you should gain access to your inflater inside your activity, you can call it with this code:

LayoutInflater li = LayoutInflater.from(context);

Where context is this or this.getActivity() if it is a Fragment. Then inflate your layour with:

View layout = li.inflate(R.layout.your_layout, null, false);

Then use addView(layout) to your container_destacado:

View containerDestacado = li.inflate(R.layout.container_destacado, null, false);
containerDestacado.addView(layout);

Hope it helps.

Solution 5 - Android

Kotlin code to do so:

 val layoutToInflate = 
 this.layoutInflater.inflate(R.layout.ly_custom_layout, 
  null)
container_destacado.addView(layoutToInflate )

Solution 6 - Android

You have the LinearLayout on which you want to inflate other childs:

LinearLayout container = (LinearLayout)parentView.findViewById(R.id.container_destacado);

Once you loaded the item.xml with an inflater, you can just use

container.addView(itemView);

Solution 7 - Android

in Kotlin with editable textview elements on item.xml

  val item = LayoutInflater.from(this).inflate(R.layout.item,null)
  val distance_N1_holder = item.findViewById<TextView>(R.id.distance_N1)
  distance_N1_holder.text = //dynamically generated value
  
  main.addView(item)

Solution 8 - Android

Below is a working code from one of my projects:

// The parent container
mNotificationOverlay = (LinearLayout) findViewById(R.id.container_destacado);   
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

for (Message message : m) {
    
    // Inflate the child layout on the fly
    final View notificationContainer = inflater.inflate(R.layout.notification_overlay_linear_layout, null);
    notificationContainer.setTag(message.getNotificationId());

    // Access children of child container
    TextView notificationOverlayTitle = (TextView) notificationContainer.findViewById(R.id.notification_title_overlay);
    TextView notificationOverlayBody = (TextView) notificationContainer.findViewById(R.id.notification_body_overlay);
    ImageButton notificationOverlayCancelButton = (ImageButton) notificationContainer.findViewById(R.id.notification_cancel_overlay);

    // Perform desired operations
    notificationOverlayCancelButton.setTag(message.getNotificationId());
    notificationOverlayTitle.setText(message.getTitle());
    notificationOverlayBody.setText(message.getNotificationBody());
    mNotificationOverlay.setVisibility(View.VISIBLE);

    // Attach any listeners
    attachListenersToCancelView(notificationOverlayCancelButton);

    // Add view to parent container
    mNotificationOverlay.addView(notificationContainer);
}

Hope that helps!

Solution 9 - Android

If someone couldn't get the addView() it's because the view is not a layout.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYerayView Question on Stackoverflow
Solution 1 - AndroidAdam RadomskiView Answer on Stackoverflow
Solution 2 - AndroidM DView Answer on Stackoverflow
Solution 3 - AndroidKunuView Answer on Stackoverflow
Solution 4 - AndroidAngmarView Answer on Stackoverflow
Solution 5 - AndroidHamed JalilianiView Answer on Stackoverflow
Solution 6 - AndroidMassimoView Answer on Stackoverflow
Solution 7 - AndroidBegYourPardonView Answer on Stackoverflow
Solution 8 - AndroidPrinceView Answer on Stackoverflow
Solution 9 - AndroidajaitaarakView Answer on Stackoverflow