自定義 View 繼承 LinearLayout,在構造函數中用 findViewById 獲取內部 TextView 並設置 OnClickListener,結果報錯或可視化編輯器渲染失敗。
構造函數執行時,XML 布局尚未完全充氣,子 View 尚不存在。 findViewById 返回 null,導致設置監聽器拋空指針。
public class CustomLayout extends LinearLayout {
private TextView tvContent;
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// 這裡不能 findViewById!
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// 此時所有子 View 已創建完成,安全獲取
tvContent = findViewById(R.id.tv_content);
tvContent.setOnClickListener(v -> {
// 處理點擊邏輯
Toast.makeText(getContext(), "TextView 被點擊", Toast.LENGTH_SHORT).show();
});
}
}
onFinishInflate() 在 LayoutInflater 完成 XML 解析、所有子 View 添加到父 View 後調用,是操作子 View 的最早安全時機。inflate(context, R.layout.xxx, this),然後立即 findViewById。onFinishInflate 即可解決。