用 Java 代碼動態建立 RelativeLayout 並加入兩個 ImageView,結果只有第二張圖片顯示,第一張被遮蓋。
RelativeLayout relativeLayout = new RelativeLayout(this);
ImageView iv1 = new ImageView(this);
iv1.setImageResource(R.drawable.fish2);
relativeLayout.addView(iv1, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
ImageView iv2 = new ImageView(this);
// 錯誤:iv.setImageResource -> 應為 iv2
iv.setImageResource(R.drawable.ctdeasytwo);
relativeLayout.addView(iv2, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
setContentView(relativeLayout);
關鍵錯誤:iv.setImageResource(...) 應為 iv2.setImageResource(...),導致第二張圖片實際未設定資源,但因兩者同尺寸疊加,視覺上只有第二個可見。
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
// 底層圖片
ImageView bottom = new ImageView(this);
bottom.setId(View.generateViewId());
bottom.setImageResource(R.drawable.fish2);
bottom.setScaleType(ImageView.ScaleType.FIT_XY);
RelativeLayout.LayoutParams bottomParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
layout.addView(bottom, bottomParams);
// 頂層透明圖片
ImageView top = new ImageView(this);
top.setImageResource(R.drawable.ctdeasyone); // 透明圖層
top.setScaleType(ImageView.ScaleType.FIT_XY);
RelativeLayout.LayoutParams topParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
// 關鍵:置中或對齊規則
topParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
layout.addView(top, topParams);
setContentView(layout);
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/bottom_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/fish2" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:scaleType="fitXY"
android:src="@drawable/ctdeasyone" />
</RelativeLayout>
setId(View.generateViewId()) 以便其他 View 參考LayoutParams (此處為 RelativeLayout.LayoutParams)addRule() 設定相對位置 (如 CENTER_IN_PARENT, ALIGN_PARENT_TOP 等)// 載入 XML 佈局為基礎
RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.base_layout, null);
// 動態添加額外圖層
ImageView overlay = new ImageView(this);
overlay.setImageResource(R.drawable.dynamic_overlay);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(overlay, params);
setContentView(layout);