74

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

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

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

知道怎么做吗?

4

3 回答 3

168

使用 aViewStub代替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();
于 2013-09-25T08:18:39.500 回答
6
ViewStub stub = (ViewStub) findViewById(R.id.text_post);
        stub.setLayoutResource(R.layout.profile_header);
        View inflated = stub.inflate();
于 2014-05-05T13:18:29.307 回答
3

在 Mono.Droid / Xamarin 这对我有用:

ViewStub stub = FindViewById<ViewStub>(Resource.Id.layout_stub);
stub.LayoutResource = Resource.Layout.whatever_layout_you_want;
stub.Inflate();
于 2016-05-09T12:54:09.283 回答