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

Android 自定義 View 綁定自定義監聽器空指針:構造器缺失 AttributeSet 導致 XML 膨脹失效

     編輯:程式設計綜合問答

現象

自定義 `TopBar` 在 XML 中使用 `findViewById` 返回 null,或監聽器 `listener` 為 null 導致點擊崩潰。

根因:構造器不完整

View 在 XML 中膨脹時,**系統調用雙參構造器 `View(Context, AttributeSet)`**。代碼中只有單參構造器,導致屬性解析失敗、子 View 未初始化。

標準三構造器模板


public class TopBar extends RelativeLayout {
    // ... 成員變量

    // 1. 代碼 new 時調用
    public TopBar(Context context) {
        this(context, null);
    }

    // 2. XML 膨脹時調用(關鍵!)
    public TopBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    // 3. 樣式屬性時調用
    public TopBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.layout_top_bar, this, true);
        ibtLeft = findViewById(R.id.ibt_left);
        ibtRight = findViewById(R.id.ibt_right);
        tvTitle = findViewById(R.id.tv_title);
        // 設置內部點擊轉發給外部監聽器
        ibtLeft.setOnClickListener(v -> { if (listener != null) listener.onLeftButtonClick(); });
        ibtRight.setOnClickListener(v -> { if (listener != null) listener.onRightButtonClick(); });
    }

    // 監聽器接口與設置方法同前
}

XML 使用示例


<com.example.TopBar
    android:id="@+id/topBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Activity 中綁定


TopBar topBar = findViewById(R.id.topBar); // 現在不再為 null
topBar.setOnTopBarClickListener(new TopBar.OnClickListener() {
    @Override public void onLeftButtonClick() { Toast.makeText(this, "Left", Toast.LENGTH_SHORT).show(); }
    @Override public void onRightButtonClick() { Toast.makeText(this, "Right", Toast.LENGTH_SHORT).show(); }
});

關鍵點總結

  • **三個構造器缺一不可**,`super(context, attrs, defStyleAttr)` 必須調用。
  • `inflate(..., this, true)` 參數 `true` 表示將膨脹的 View 添加到 `this` (TopBar) 中。
  • 監聽器調用前**必須非空判斷**,避免 XML 預覽/初始化階段觸發崩潰。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved