如何以编程方式在 Android 中包含布局? [英] How can I programmatically include layout in Android?
本文介绍了如何以编程方式在 Android 中包含布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种以编程方式包含布局的方法,而不是像我的示例中那样使用 XML 标记 include
:
I'm looking for a way to include a layout programmatically instead of using the XML tag include
like in my example:
<include layout="@layout/message"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.75"/>
请以编程方式更改此参数layout="@layout/message".
Need to change this parameter "layout="@layout/message" programmatically, please.
知道怎么做吗?
推荐答案
使用 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" />
然后在代码中,获取对存根的引用,设置其布局资源,并对其进行膨胀:
Then in code, get a reference to the stub, set its layout resource, and inflate it:
ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(R.layout.whatever_layout_you_want);
View inflated = stub.inflate();
这篇关于如何以编程方式在 Android 中包含布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文