onCreate 中 addView(customView) → 正常顯示。onWindowFocusChanged 中 addView(customView) → 不顯示(寬高為 0)。onWindowFocusChanged 回調時,View 根佈局可能尚未完成佈局傳遞,customView 的 LayoutParams 未被正確解析,導致寬高為 0。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. 先添加到容器
container.addView(customView); // container 是 LinearLayout/FrameLayout 等
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
// 2. 此時 View 樹已佈局完成,可安全獲取寬高並設置
int w = container.getWidth();
int h = container.getHeight();
customView.setLayoutParams(new ViewGroup.LayoutParams(w, h));
// 或 customView.measure(...); customView.layout(...);
customView.requestLayout(); // 觸發重繪
}
}
getWidth()/getHeight() 已有效。onSizeChanged 畫圖),必須在尺寸確定後調用 requestLayout() 或 invalidate()。
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
container.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// 此處安全獲取寬高並設置 customView
}
});
比 onWindowFocusChanged 更精準,不依賴焦點變化。