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

26

我知道如何使用include标签,但我遇到了一个问题。

基本上,我想在xml中定义一个布局,其中有几个TextView和一个ImageView。然后,我想迭代一个数组,并根据数组中的内容填充xml布局中的字段(数组在运行时填充)。因此,会生成多个xml布局的副本,并使用唯一的数据填充字段。现在我不知道如何以这种方式重复使用LinearLayout,因为其中的TextViewImageView具有固定的id,并且我需要制作此布局的多个副本。

有没有办法膨胀资源,然后制作它的副本,可以工作……所以

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

很遗憾,没有这样的构造函数。

唯一的其他方法是全部以编程方式完成,但我更喜欢在XML中具有视图和LinearLayout的属性,而不是在代码中。就像我希望LinearLayout是一个模板,可以复制多个副本...真的不确定是否可能。

2个回答

44

你可以轻松地完成这个任务,你只需要将其分解。首先,加载你想要插入动态视图的布局。然后,填充你的子视图并根据需要多次重复此操作。接着,将该视图添加到父布局中,最后将活动的内容视图设置为父视图。

下面是一个例子:

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>

非常感谢!问题解决了……我想我需要理解不同的inflate(...)调用。 - gunboatmedia
1
谢谢!这也是一个很好的Inflater示例! - Mailis Toompuu
1
有没有一种方法可以在循环期间简单地复制布局,而不是在每次迭代中使用inflator.inflate()? 在我看来,与简单复制相比,充气非常昂贵。 - SMBiggs
是的,这就是了。谢谢 - iibrahimbakr
有没有办法在Fragment中使用它?getActivity().setContentView(parent会搞砸整个事情,但我看到了结果。 此外,在实施这个之后,我似乎经常遇到这个错误 android.content.res.Resources$NotFoundException: String resource ID #0x7f0e00a2 - KasparTr

6

如果有人仍在寻找类似的解决方案,显然您也可以直接在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接