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

Android 讓兩個 ImageView 尺寸同步:XML 屬性 layout_alignRight/Bottom 實現無代碼綁定

     編輯:程式設計綜合問答

需讓第二個 ImageView 尺寸跟隨第一個,純 XML 即可實現,無需代碼監聽尺寸變化。

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 對應邊對齊。
  • 第二個 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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved