我正在寻找一种以编程方式包含布局的方法,而不是像我的示例中那样使用 XML 标记 include
:
<include layout="@layout/message"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.75"/>
请以编程方式更改此参数“layout="@layout/message”。
知道怎么做吗?
最佳答案
使用 ViewStub
代替 include
:
<ViewStub
android:id="@+id/layout_stub"
android:inflatedId="@+id/message_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.75" />
然后在代码中,获取对 stub 的引用,设置其布局资源,并对其进行扩充:
ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(R.layout.whatever_layout_you_want);
View inflated = stub.inflate();
关于android - 如何以编程方式在 Android 中包含布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18999601/