首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android HorizontalScrollView 動態添加多個 ImageView 的正確佈局結構

     編輯:程式設計綜合問答

問題原因

HorizontalScrollView 繼承自 FrameLayout,**只能有一個直接子視圖**。直接多次 addView(imageView) 會拋出 IllegalStateException: The specified child already has a parent 或只有最後一個生效。

正確結構:內嵌 LinearLayout


// Java 代碼動態構建
HorizontalScrollView scrollView = new HorizontalScrollView(this);
LinearLayout container = new LinearLayout(this);
container.setOrientation(LinearLayout.HORIZONTAL);
container.setLayoutParams(new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT));

scrollView.addView(container); // 滾動視圖唯一子視圖

// 循環添加 ImageView 到 container
for (int i = 0; i < imageResIds.length; i++) {
    ImageView iv = new ImageView(this);
    iv.setImageResource(imageResIds[i]);
    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
    // 設置邊距
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            300, 200); // 固定寬高或 WRAP_CONTENT
    params.setMargins(0, 0, 16, 0);
    iv.setLayoutParams(params);
    container.addView(iv);
}

// 加入根佈局
rootLayout.addView(scrollView);

XML 靜態佈局對照


<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <LinearLayout
        android:id="@+id/image_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="16dp">
        <!-- ImageView 由代碼動態添加 -->
    </LinearLayout>

</HorizontalScrollView>

代碼中 findViewById(R.id.image_container) 獲取 LinearLayout 再 addView。

進階:使用 RecyclerView 替代(推薦)

大量圖片、需回收複用、支援點擊事件時,HorizontalScrollView + LinearLayout 易 OOM 且無視圖回收。現代做法:


// 佈局
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/horizontal_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

// Adapter 綁定圖片,自動回收、預載、支援點擊

總結

  • HorizontalScrollView 僅接受**一個**直接子視圖。
  • 動態添加多視圖時,先添加一個 LinearLayout(horizontal) 作為容器,再向容器添加子視圖。
  • 列表型橫向滾動優先選 RecyclerView,性能與體驗更優。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved