簡體   English   中英

如何在布局中創建“ i”個對象(通過循環)?

[英]How to create 'i' number of objects in a layout (by looping)?

我需要創建i一些photo_view每一次(循環)給它一個特殊的量。 每次的photo_view數量將有所不同。 我到底應該在代碼中做什么?

我的xml文件:

<?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:custom="http://schemas.android.com/tools"
        android:id="@+id/coordinatorLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/black">

        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <com.github.chrisbanes.photoview.PhotoView
                    android:id="@+id/photo_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"/>
            </LinearLayout>
        </HorizontalScrollView>

        <ImageView
            android:id="@+id/exit_btn"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_margin="20dp"
            android:clickable="true"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_back_ltr" />

    </android.support.design.widget.CoordinatorLayout>

您正在尋找將視圖動態添加到ViewGroup方法。 這是通過代碼而不是XML來完成的。

在一般情況下,有兩種方式來添加view動態,無論是在充氣一些布局文件view ,然后這個添加view到父viewgroupLinearLayout通過調用為前) add在這個父視圖的方法。

或者,通過定義該視圖的new對象並向其添加所需的所有參數,然后將其添加到父viewgroup

在此處查看有關方法1的示例

在此處查看方法2的示例


在您的情況下,您可以創建一個僅包含自定義視圖com.github.chrisbanes.photoview.PhotoView以及所有所需參數的新layout.xml文件。 然后為父linearlayout添加一個ID

        <LinearLayout
            android:"@+id/parentViewGroup"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">


        </LinearLayout>

然后在代碼中按計數循環,然后將自定義展開視圖添加到父級。 像這樣:

View inflatedView = View.inflate(context, yourViewXML, null);
LinearLayout parentViewGroup = findViewById(R.id.parentViewGroup);

for(int i = 0 ; i<count ; i++){
  parentViewGroup.add(inflatedView);
}

暫無
暫無

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

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