需讓第二個 ImageView 尺寸跟隨第一個,純 XML 即可實現,無需代碼監聽尺寸變化。
<RelativeLayout ...>
<ImageView
android:id="@+id/first_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/frame" />
<ImageView
android:id="@+id/second_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/first_imageview"
android:layout_alignLeft="@id/first_imageview"
android:layout_alignRight="@id/first_imageview" <!-- 關鍵:右邊對齊 -->
android:layout_alignBottom="@id/first_imageview" <!-- 關鍵:底部對齊 -->
android:scaleType="fitXY" />
</RelativeLayout>
layout_alignRight/Bottom/Top/Left 強制第二個 View 的四邊與第一個 View 對應邊對齊。wrap_content 在對齊約束下失效,實際尺寸由約束決定,與第一個 View 完全一致。scaleType="fitXY" 確保圖片拉伸填滿綁定尺寸。firstView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
ViewGroup.LayoutParams lp = secondView.getLayoutParams();
lp.width = right - left;
lp.height = bottom - top;
secondView.setLayoutParams(lp);
});
XML 對齊屬性最簡潔高效,動態場景用 LayoutChangeListener。