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

Android Dialog 獲取根視圖 ListView 空指針修復:View.inflate 替代 getCurrentFocus()

     編輯:程式設計綜合問答

現象:Dialog 使用 XML 佈局(根節點為 ListView),在 onCreateDialog 中嘗試 d.getCurrentFocus().getRootView() 獲取 ListView 設置 Adapter,拋出 NPE。

根因:Dialog 尚未顯示,無焦點視圖

  • Dialog 創建後、show() 前,**沒有焦點**,getCurrentFocus() 返回 null。
  • XML 根節點為 ListView 時,無法通過 findViewById 獲取(無 ID)。

修正方案:View.inflate 直接膨脹佈局獲取根 View

@Override
protected Dialog onCreateDialog(int id) {
    if (id == ADDPLAYERDIALOG) {
        Dialog dialog = new Dialog(this);
        // 關鍵:inflate 佈局,直接獲得根 ListView
        ListView listView = (ListView) View.inflate(this, R.layout.training_dialog, null);
        dialog.setContentView(listView); // 設置為 Dialog 內容視圖
        
        ListAdapter adapter = new ArrayAdapter<>(
            this, android.R.layout.simple_list_item_1, createNamesList());
        listView.setAdapter(adapter);
        
        return dialog;
    }
    return super.onCreateDialog(id);
}

進階:DialogFragment + ViewBinding(現代標準)

public class NameListDialogFragment extends DialogFragment {
    private DialogNameListBinding binding;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        binding = DialogNameListBinding.inflate(getLayoutInflater());
        binding.listView.setAdapter(new ArrayAdapter<>(
            requireContext(), android.R.layout.simple_list_item_1, createNamesList()));
        return new AlertDialog.Builder(requireContext())
            .setView(binding.getRoot())
            .create();
    }
}

關鍵點

  • View.inflate(context, layoutRes, null) 返回佈局根 View,**無需父容器**。
  • Dialog 設置內容視圖用 setContentView(View) 而非 layoutRes。
  • 避免在 Dialog 未 show 時調用 getCurrentFocus()/findViewById()。

掌握 View.inflate 模式,優雅解決 Dialog 根視圖獲取難題。

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