HorizontalScrollView 繼承自 FrameLayout,**只能有一個直接子視圖**。直接多次 addView(imageView) 會拋出 IllegalStateException: The specified child already has a parent 或只有最後一個生效。
// 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);
<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。
大量圖片、需回收複用、支援點擊事件時,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,性能與體驗更優。