我希望通过 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
被膨胀在Activity
的onCreate
方法中(这取决于应用程序的条件)。
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可以解决问题。