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

Android 監聽佈局尺寸變化:覆寫 onLayout 方法在尺寸確定後調整

     編輯:程式設計綜合問答

自訂 View 覆寫 onLayout,在 changed 為 true 時執行尺寸調整邏輯,回應 AdMob 等動態視圖變化。

程式碼

View customView = new View(this) {
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            // 尺寸已確定,執行調整邏輯
            adjustLayout(right - left, bottom - top);
        }
    }
};

說明

  • onLayout 在 View 及其子視圖完成佈局後呼叫,changed 表示尺寸/位置是否變更。
  • 適用於需在尺寸確定後計算位置、啟動動畫、通知其他元件等場景。
  • 若為現有 View 子類,直接在該類別覆寫即可。

替代:ViewTreeObserver.OnGlobalLayoutListener

view.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
    // 佈局完成後回調(可能多次觸發)
    if (view.getWidth() > 0) { /* ... */ }
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved