以编程方式替换Android的<include />标记的"layout"

Ami*_*ade 6 xml android

我想动态/编程地更改layout我的<include/>标签.

我有一个layout我想重复使用的主要内容,但内容应该动态更改.

<?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> 
Run Code Online (Sandbox Code Playgroud)

上面是我正在使用的xml,我假设你需要找到include的id然后以编程方式更改它.

提前致谢.

Rah*_*kar 8

只需更改代码即可

// 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);
Run Code Online (Sandbox Code Playgroud)

它对我有用.


Ami*_*ade 2

几个月前我找到了答案。您只需要使用 ViewStub 并填充适当的 ViewStub 即可。

  • 请注意提供解决方案,而不是像这样结束。 (5认同)