簡體   English   中英

多次包含相同的布局

[英]Include same layout multiple times

我有一個共同的布局(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>

在XML中定義的ID必須是唯一的。 您包含兩個具有包含相同ID的視圖的布局。

以下是修復它的方法。

ps除非您的第一個布局文件中沒有包含更多代碼,否則該合並標記將毫無用處。

正如btse所說,XML中的ID必須是唯一的。 它可以通過這種方式實現:

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

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

有關如何訪問這兩個包含視圖中的元素的信息,您可以查看博客文章。

這就是我在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));

我通過將RelativeLayout的layout_height設置為250dp來修復,因為它們是重疊的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM