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

Android GridView Item 點擊與 CheckBox 衝突?關閉 CheckBox 焦點屬性,統一由 Item 點擊處理選中狀態

     編輯:程式設計綜合問答

GridView 加載含 CheckBox 的 Item,若 CheckBox 可點擊會攔截觸摸事件,導致 `OnItemClickListener` 失效。解法:禁用 CheckBox 焦點/點擊,邏輯集中在 Item 層。

關鍵屬性(XML)

<CheckBox
    android:id="@+id/cb_select"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:clickable="false"
    android:background="@null" />

Adapter 中處理選中邏輯

public class MyAdapter extends BaseAdapter {
    private final Set checkedPositions = new HashSet<>();
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.cbSelect.setChecked(checkedPositions.contains(position));
        return convertView;
    }
    
    public void toggle(int position) {
        if (checkedPositions.contains(position)) checkedPositions.remove(position);
        else checkedPositions.add(position);
        notifyDataSetChanged();
    }
    
    public List getCheckedPositions() {
        return new ArrayList<>(checkedPositions);
    }
}

Activity/Fragment 中綁定點擊

gridView.setOnItemClickListener((parent, view, position, id) -> {
    adapter.toggle(position);
    // 更新底部預覽/發送按鈕狀態
    updateBottomBar(adapter.getCheckedPositions().size());
});

效果對標 QQ 相冊選圖

  • 點擊任意區域(含圖片、文字、空白)切換選中態。
  • CheckBox 僅作視覺指示,不響應觸摸。
  • 底部浮層實時顯示選中數量,點擊進入預覽/發送流程。

此模式避免事件分發衝突,代碼清晰,擴展性強(可加長按進入選擇模式、全選/反選等)。

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