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

sla*_*007 60 parameters android include android-layout xamarin.android

我正在寻找一种方法来以编程方式包含布局,而不是include像我的示例中那样使用XML标记 :

  <include layout="@layout/message"  
           android:layout_width="match_parent" 
           android:layout_height="match_parent" 
           android:layout_weight="0.75"/>
Run Code Online (Sandbox Code Playgroud)

需要以编程方式更改此参数" layout ="@ layout/message ".

知道怎么做吗?

kco*_*ock 146

使用a 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" />
Run Code Online (Sandbox Code Playgroud)

然后在代码中,获取对存根的引用,设置其布局资源,并对其进行膨胀:

ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(R.layout.whatever_layout_you_want);
View inflated = stub.inflate();
Run Code Online (Sandbox Code Playgroud)


pat*_*135 5

ViewStub stub = (ViewStub) findViewById(R.id.text_post);
        stub.setLayoutResource(R.layout.profile_header);
        View inflated = stub.inflate();
Run Code Online (Sandbox Code Playgroud)