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

Android Dialog 中 ListView 空指針異常:findViewById 作用域錯誤修正

     編輯:程式設計綜合問答

在 Dialog 中使用 findViewById(R.id.list) 直接呼叫 Activity 的方法,會在 Activity 佈局中尋找 ID 為 list 的視圖,而非 Dialog 佈局,導致回傳 null。修正:對 Dialog 實例呼叫 findViewById。

錯誤代碼


Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.tone_dialog);

// 錯誤:在 Activity 尋找
ListView toneList = (ListView) findViewById(R.id.list); // 回傳 null
// 後續 toneList.setAdapter(...) 拋出 NPE

正確代碼


Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.tone_dialog);

// 正確:在 Dialog 佈局中尋找
ListView toneList = (ListView) dialog.findViewById(R.id.list);
toneList.setAdapter(adapter);
dialog.show();

完整實作範例


public void showToneDialog() {
    Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.tone_dialog);
    dialog.setTitle(R.string.tonePromptTitle);
    
    // 關鍵:dialog.findViewById
    ListView toneList = dialog.findViewById(R.id.list);
    
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        this, R.array.tones, android.R.layout.simple_list_item_1);
    toneList.setAdapter(adapter);
    
    toneList.setOnItemClickListener((parent, view, position, id) -> {
        String selectedTone = (String) parent.getItemAtPosition(position);
        // 處理選擇
        dialog.dismiss();
    });
    
    dialog.show();
}

AlertDialog.Builder 簡化寫法(推薦)


new AlertDialog.Builder(this)
    .setTitle(R.string.tonePromptTitle)
    .setAdapter(ArrayAdapter.createFromResource(this, R.array.tones, android.R.layout.simple_list_item_1),
        (dialog, which) -> {
            String selectedTone = getResources().getStringArray(R.array.tones)[which];
            // 處理選擇
        })
    .show();

核心原則

視圖尋找作用域必須與視圖所屬容器一致
Activity 佈局用 Activity.findViewById、Dialog 佈局用 Dialog.findViewById、Fragment 佈局用 View.findViewById(在 onCreateView 返回的根視圖上)。

常見衍生錯誤

  • LayoutInflater.inflate 返回的 View 上找子視圖 → 正確
  • Fragment.onCreateView 中用 getActivity().findViewById → 錯誤(應用 view.findViewById)
  • RecyclerView.ViewHolder 建構子中用 itemView.findViewById → 正確

牢記「誰持有佈局,誰負責 findViewById」,即可徹底避免此類空指針問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved