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

时间:2013-09-25 08:12:20

标签: android android-layout parameters include xamarin.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 个答案:

答案 0 :(得分:140)

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

答案 1 :(得分:5)

ViewStub stub = (ViewStub) findViewById(R.id.text_post);
        stub.setLayoutResource(R.layout.profile_header);
        View inflated = stub.inflate();

答案 2 :(得分:3)

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

ViewStub stub = FindViewById<ViewStub>(Resource.Id.layout_stub);
stub.LayoutResource = Resource.Layout.whatever_layout_you_want;
stub.Inflate();