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

时间:2011-10-27 13:27:09

标签: android xml layout reusability

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

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

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

LinearLayout one = new LinearLayout(inflater.inflate(R.layout.home, container, false));

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

唯一的另一种方法是以编程方式完成所有操作,但我更倾向于在xml中而不是在代码中使用视图和LinearLayout的属性。这就像我希望LinearLayout成为一个模板,你可以复制我猜...真的不确定这是否可能。

2 个答案:

答案 0 :(得分: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);

这是我插入的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>

这是我扩充,填充和动态插入的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>

答案 1 :(得分:7)

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

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);

来源:Romain Guy