2012-06-27 79 views
0

我知道这看起来可能是一个奇怪的问题,但对于我来说,如果我可以从主XML文件指向的一组其他XML文件构成布局XML,那将非常方便。原因是我有这个XML中定义的一些列表项视图,并希望在其他地方重用。它是可能的或唯一的方法就是应对和粘贴它?创建由其他XML文件组成的XML布局文件?

回答

3

您可以使用“包括”标签

<LinearLayout> 
    <include layout="@layout/toinclude1" /> 
    <include layout="@layout/toinclude1" /> 
</LinearLayout> 

另一种方式是ViewStub在一个单一的布局不同的布局文件。如果要加载异步布局,你可以有:

<ViewStub android:id="@+id/stub" 
      android:inflatedId="@+id/subTree" 
      android:layout="@layout/mySubTree" 
      android:layout_width="120dip" 
      android:layout_height="40dip" /> 

而且在你的代码,当你想你可以写:

ViewStub stub = (ViewStub) findViewById(R.id.stub); 
View inflated = stub.inflate(); 

对于一些参考:http://developer.android.com/reference/android/view/ViewStub.html

1

说你有像这样的header.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    style="@style/somestyle" > 

    <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" 
     android:clickable="false" 
     android:paddingLeft="15dip" 
     android:scaleType="center" 
     android:src="@drawable/logo" /> 

</LinearLayout> 

您可以使用<include layout="@layout/header"/>以在多种布局中包含页眉布局代码。 main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/home_root" 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"> 
      <include layout="@layout/header"/> 
</LinearLayout>