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

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

  <include layout="@layout/message"  
           android:layout_width="match_parent" 
           android:layout_height="match_parent" 
           android:layout_weight="0.75"/>

请以编程方式更改此参数“ layout =“ @ layout / message”。

任何想法如何做到这一点?

3个解决方案
138 votes

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

然后在代码中,获得对存根的引用,设置其布局资源,然后对其进行充气:

ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(R.layout.whatever_layout_you_want);
View inflated = stub.inflate();
kcoppock answered 2019-10-08T10:56:24Z
5 votes
ViewStub stub = (ViewStub) findViewById(R.id.text_post);
        stub.setLayoutResource(R.layout.profile_header);
        View inflated = stub.inflate();
patel135 answered 2019-10-08T10:56:42Z
3 votes

在Mono.Android / Xamarin中,这对我有用:

ViewStub stub = FindViewById<ViewStub>(Resource.Id.layout_stub);
stub.LayoutResource = Resource.Layout.whatever_layout_you_want;
stub.Inflate();
Daniele D. answered 2019-10-08T10:57:06Z
translate from https://stackoverflow.com:/questions/18999601/how-can-i-programmatically-include-layout-in-android