且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式在 Android 中包含布局?

更新时间:2023-02-12 18:04:19

使用 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();