自訂 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.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
// 佈局完成後回調(可能多次觸發)
if (view.getWidth() > 0) { /* ... */ }
});