Reputation: 1171
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.
Upvotes: 9
Views: 9793
Reputation: 1
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
Upvotes: 0
Reputation: 1818
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.
Upvotes: 12
Reputation: 1171
I found the answer a couple of months ago. You just need to use a ViewStub and inflate the appropriate one.
Upvotes: 2
Reputation: 12358
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
Upvotes: 0