包括使用合并标记和ViewStub的视图

8

我希望通过 ViewStub 元素为我的 TableLayout 添加一些额外的行。这是我的 Activity 的布局:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root_table_layout">

    <TableRow>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Row 1"/>
    </TableRow>

    <TableRow>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Row 2"/>
    </TableRow>

    <ViewStub
        android:id="@+id/view_stub_1"
        android:layout="@layout/merge_table_1"/>

    <ViewStub
        android:id="@+id/view_stub_2"
        android:layout="@layout/merge_table_2"/>

</TableLayout>

无论是view_stub_1还是view_stub_2被膨胀在ActivityonCreate方法中(这取决于应用程序的条件)。

ViewStub应该膨胀一个以<merge>标记作为根元素定义的布局。就像这样:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TableRow>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Row 5"/>
    </TableRow>

    <TableRow>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Row 6"/>
    </TableRow>

</merge>

但是当Activity即将启动时,我遇到了这个异常:

merge只能与有效的ViewGroup根和attachToRoot=true一起使用-使用getLayoutInflater可以解决问题。

1个回答

9

目前看来,<merge>标签还不支持ViewStub元素:

ViewStub唯一的缺点是目前不支持<merge>标签。

Romain Guy在布局技巧方面的文章

最终,我使用ActivityLayoutInflater将其他行包含到TableLayout中:

ViewGroup rootTableLayout = (ViewGroup) findViewById(R.id.root_table_layout);
getLayoutInflater().inflate(R.layout.merge_table_1, rootTableLayout, true);

由于我只想在 ViewGroup 的末尾附加几个 TableRows,所以这个解决方案是可行的。对于更复杂的情况(动态地在 TableLayout 中间包含 TableRows),我仍然不知道什么是适当的方法。


3
几年后似乎仍存在问题。 - William Reed

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