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

Android 自定義 ListView 項目點擊無響應:CheckBox 搶奪焦點導致 onItemClick 失效

     編輯:程式設計綜合問答

現象

自定義列表項包含 CheckBox,設置 OnItemClickListener 但點擊項目無反應,onListItemClick / onItemClick 不被調用。

根本原因:焦點搶奪

CheckBox (及 Button、ImageButton 等) 默認 focusable="true",會攔截觸摸事件,導致 ListView 無法檢測到項目點擊。

解決方案:設置 CheckBox 不可聚焦




    android:focusableInTouchMode="false" 
    android:gravity="center"
    android:padding="5dip" />

驗證:其他常見焦點搶奪控件

控件默認 focusable解決
CheckBoxtrueandroid:focusable="false"
Button / ImageButtontrueandroid:focusable="false"
EditTexttrue列表項避免用 EditText,或 focusableInTouchMode="false"
RatingBartrueandroid:focusable="false"
Switch / ToggleButtontrueandroid:focusable="false"

進階:若需 CheckBox 可點擊且項目也可點擊


// 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();
});

原理:descendantFocusability

  • beforeDescendants (默認):子視圖優先獲取焦點
  • afterDescendants:父視圖優先,子視圖次之
  • blocksDescendants:阻斷子視圖獲取焦點,父視圖獨佔焦點 → 列表項點擊正常工作

現代 RecyclerView 同理

RecyclerView 項目佈局同樣需設置 android:focusable="false" 於可聚焦子控件,或根佈局加 blocksDescendants。

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