自定義列表項包含 CheckBox,設置 OnItemClickListener 但點擊項目無反應,onListItemClick / onItemClick 不被調用。
CheckBox (及 Button、ImageButton 等) 默認 focusable="true",會攔截觸摸事件,導致 ListView 無法檢測到項目點擊。
android:focusableInTouchMode="false"
android:gravity="center"
android:padding="5dip" />
| 控件 | 默認 focusable | 解決 |
|---|---|---|
| CheckBox | true | android:focusable="false" |
| Button / ImageButton | true | android:focusable="false" |
| EditText | true | 列表項避免用 EditText,或 focusableInTouchMode="false" |
| RatingBar | true | android:focusable="false" |
| Switch / ToggleButton | true | android:focusable="false" |
// 1. CheckBox 設置不可聚焦
android:focusable="false"
android:focusableInTouchMode="false"
// 2. 項目佈局根視圖設置可點擊
// 3. ListView 設置選擇模式 (可選)
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener((parent, view, position, id) -> {
// 項目點擊邏輯
// 可手動切換 CheckBox 狀態
CheckBox cb = view.findViewById(R.id.selectedCheckbox);
cb.toggle();
});
beforeDescendants (默認):子視圖優先獲取焦點afterDescendants:父視圖優先,子視圖次之blocksDescendants:阻斷子視圖獲取焦點,父視圖獨佔焦點 → 列表項點擊正常工作RecyclerView 項目佈局同樣需設置 android:focusable="false" 於可聚焦子控件,或根佈局加 blocksDescendants。