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

自定義 LinearLayout 內 TextView 點擊事件失效?onFinishInflate 才是正確時機

     編輯:程式設計疑難解答

問題場景

自定義 View 繼承 LinearLayout,在構造函數中用 findViewById 獲取內部 TextView 並設置 OnClickListener,結果報錯或可視化編輯器渲染失敗。

錯誤原因

構造函數執行時,XML 布局尚未完全充氣,子 View 尚不存在。 findViewById 返回 null,導致設置監聽器拋空指針。

正確做法:重寫 onFinishInflate()

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 的最早安全時機。
  • 若需在代碼中動態添加 View,可在構造函數最後調用 inflate(context, R.layout.xxx, this),然後立即 findViewById。
  • 可視化編輯器渲染失敗通常因構造函數拋異常,移至 onFinishInflate 即可解決。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved