Android使用布局作为模板来创建多个布局实例

gun*_*dia 25 xml layout android reusability

好的,所以我理解如何使用include标签,但我遇到了问题.

基本上我想要在xml中定义一个布局,其中有几个TextViews和一个ImageView.然后我想迭代一个数组并根据数组中的whats(在运行时填充)填充xml布局中的字段.从而制作xml布局的多个副本并使用唯一数据填充字段.现在我不知道如何LinearLayout以这种方式重复使用它,因为其中的TextViews和ImageViews具有常量id,我需要制作此布局的多个副本.

有没有办法给资源充气,然后复制一下,这样就行了......所以

LinearLayout one = new LinearLayout(inflater.inflate(R.layout.home, container, false));
Run Code Online (Sandbox Code Playgroud)

^遗憾的是没有这样的构造函数.

唯一的另一种方法是以编程方式完成所有操作,但我更愿意拥有视图的属性和LinearLayoutxml而不是代码.这就像我想要LinearLayout成为一个模板,你可以复制我猜...真的不确定这是否可能.

Cra*_*igy 43

你可以很容易地做到这一点,你只需要分解它.首先,加载要插入动态视图的布局.然后,您可以根据需要多次填充子视图并填充它.然后将视图添加到父布局,最后将活动的内容视图设置为父视图.

这是一个例子:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);

for (int i = 0; i < 3; i++) {
    View custom = inflater.inflate(R.layout.custom, null);
    TextView tv = (TextView) custom.findViewById(R.id.text);
    tv.setText("Custom View " + i);
    parent.addView(custom);
}

setContentView(parent);
Run Code Online (Sandbox Code Playgroud)

这是我插入的main.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

这是我扩充,填充和动态插入的custom.xml视图:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

希望这个例子有帮助!


小智 7

对于仍在寻找类似解决方案的人,显然你也可以include直接在xml中使用,但仍然可以在代码中引用它们:

LinearLayout row1 = (LinearLayout) findViewById(R.id.row1)
TextView text1 = row1.findViewById(R.id.text);

LinearLayout row2 = (LinearLayout) findViewById(R.id.row2)
TextView text2 = row2.findViewById(R.id.text);
Run Code Online (Sandbox Code Playgroud)

来源:罗曼盖伊