Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace `layout` of an <include/> tag programmatically for Android

Tags:

android

xml

I want to change the layout of my <include/> tag dynamically/programmatically.

I have a main layout that I want to re-use but the contents should change dynamically.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white_background"
    android:orientation="vertical" >
    <include
        android:id="@+id/main_container"
        layout="REPLACE_THIS" />
</android.support.v4.widget.SwipeRefreshLayout> 

Above is the xml that I am using, I am assuming that you will need to find the id of the include and then change it programmatically.

Thanks in advance.

like image 275
Amilcar Andrade Avatar asked Mar 13 '15 22:03

Amilcar Andrade


2 Answers

Just change the code in the respective java file (e.g. MainActivity.java):

// Retrieve layout:
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main_container); 

// Instantiate & use inflater:
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.your_layout, null);

// Clear & set new views:
mainLayout.removeAllViews();
mainLayout.addView(layout);

It worked for me.

like image 118
Rahul Giradkar Avatar answered Sep 29 '22 08:09

Rahul Giradkar


I found the answer a couple of months ago. You just need to use a ViewStub and inflate the appropriate one.

like image 40
Amilcar Andrade Avatar answered Sep 29 '22 08:09

Amilcar Andrade