多次包含相同的布局

时间:2013-10-05 08:03:45

标签: android android-layout

我有一个共同的布局(common.xml),我希望在另一个布局(layout_a.xml)中多次包含它。但它只给我看了一次。为什么?

common.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@android:drawable/alert_light_frame">

        <ImageView

            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:id="@+id/imageView"

            android:src="@drawable/test"

            android:scaleType="centerCrop" />

        <TextView

            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_below="@+id/imageView"
            android:id="@+id/textView"
            android:text="test"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="10dp" />
    </RelativeLayout>
</merge>

layout_a.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/common" />

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

4 个答案:

答案 0 :(得分:11)

在XML中定义的ID必须是唯一的。您包含两个具有包含相同ID的视图的布局。

Here是你如何修复它。

P.S。除非您的第一个布局文件中没有包含更多代码,否则该合并标记将毫无用处。

答案 1 :(得分:6)

正如btse所说,XML中的ID必须是唯一的。 它可以通过这种方式实现:

<include android:id="@+id/common1"
    layout="@layout/common" />

<include android:id="@+id/common2"
    layout="@layout/common" />

有关如何访问这两个包含视图中的元素的信息,您可以查看this博文。

答案 2 :(得分:0)

这就是我在Inflater项目中所做的事情。 test1只是一个由LinearLayout(Vertical)(带有文本和按钮)组成的布局,在这种情况下,mainofferslayout是带有图像的主布局。

// Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_offers_display, container, false);

    View inflatedLayout = inflater.inflate(R.layout.test1, (ViewGroup) view, false);
    LinearLayout ll = (LinearLayout) view.findViewById(R.id.mainofferslayout);

    ll.addView(inflater.inflate(R.layout.test1, (ViewGroup) view, false));
    ll.addView(inflater.inflate(R.layout.test1, (ViewGroup) view, false));
    ll.addView(inflater.inflate(R.layout.test1, (ViewGroup) view, false));

答案 3 :(得分:-1)

我通过将RelativeLayout的layout_height设置为250dp来修复,因为它们是重叠的。

相关问题