9

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.

2
  • 2
    See this post, it may contain your solution. Commented Mar 13, 2015 at 22:59
  • 1
    I've found this other question and it has been answered stackoverflow.com/a/18999694/788205 Commented Oct 10, 2015 at 3:44

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Please care to provide solution rather just winding up like this.
Can you please add the solution?
0

You can do in this manner

RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id. main_container); 
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View layout = inflater.inflate(R.layout.your_layout, mainLayout, true);
mainLayout.removeAllView();
mainLayout.addView(layout);

Before adding the view you have to remove all the views first and then inflate the layout in it as shown above

Comments

0

Too late for response but after some exhausting time I figure out a simple way to re-use xml file inside a parent layout. Just add the #include tag in your xml then don't forget to removeallviews inside the java class. Then it works. Follow the procedures above but again and again don't forget to add include tag in your parent xml file. Otherwise it won't work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.