我如何在程序中引入Android的布局?布局、程序、如何在、Android

2023-09-05 06:47:25 作者:执酒共酌

我在寻找一种方法,包括布局编程而不是使用XML标记包括就像在我的例子:

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"/>

需要改变这个参数布局=@布局/信息编程,请。

不知道如何做到这一点?

Any idea how to do this?

推荐答案

使用 ViewStub 而不是包括

<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" />

然后在code,得到一个参考存根,设置它的布局资源,它充气:

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