帮助:如何在我的应用Android中以编程方式“包含(在xml中)”?

时间:2011-05-11 08:44:15

标签: android android-layout android-xml

我在layout.xml中有这一行:

<include android:id="@+id/promo1" android:layout_width="fill_parent"
         android:layout_height="fill_parent" layout="@layout/one_promo">
</include>
<include android:id="@+id/promo2" android:layout_width="fill_parent"
         android:layout_height="fill_parent" layout="@layout/one_promo">
</include>
<include android:id="@+id/promo3" android:layout_width="fill_parent"
         android:layout_height="fill_parent" layout="@layout/one_promo">
</include>

我想在我的Java代码中以编程方式执行此操作。

请帮忙吗?

提前致谢

1 个答案:

答案 0 :(得分:3)

使用LayoutInflater,如下所示

在xml中定义相对布局

<RelativeLayout android:id="@+id/mylayout" android:layout_width="fill_parent"
         android:layout_height="fill_parent" />

将其映射到Java代码

RelativeLayout mynewlayout = (RelativeLayout) findById(R.id.mylayout);

使用Layout Inflater

LayoutInflater layoutInflater = (LayoutInflater) 
        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
mynewlayout.addView(0, layoutInflater.inflate(R.layout.one_promo, this, false) );