List item with CheckBox not clickable

前端 未结 9 1930
误落风尘
误落风尘 2020-12-31 01:12

I have a list item which contains a CheckBox, and I want to be able to click on the CheckBox and on the list item itself. Unfortunately, there seems to be some sort of confl

9条回答
  •  佛祖请我去吃肉
    2020-12-31 01:47

    I solved the problem this way. I implemented OnClickListener inside the Adapter and not in the Fragment/Activity and it works well. Now I can use ListView with checkboxes and can click on both. Here is my code:

    public class MyFragment extends Fragment
    {
        ...
    
        private void setView()
        {
            ListView listView = (ListView) mRootView.findViewById(R.id.listview);
            mItems = DatabaseManager.getManager().getItems();
    
            // create adapter
            if(listView.getAdapter()==null)
            {
                MyAdapter adapter = new MyAdapter(this, mItems);
                try
                {
                    listView.setAdapter(adapter);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                    return;
                }
            } 
            else 
            {
                try
                {
                    ((MyAdapter) listView.getAdapter()).refill(mItems);
                    BaseAdapter adapter = (BaseAdapter) listView.getAdapter();
                    listView.requestLayout();
                    adapter.notifyDataSetChanged();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                    return;
                }
            }
    
            // handle listview item click
            listView.setClickable(true);
            // listView.setOnItemClickListener(...); // this method does not work in our case, so we can handle that in adapter
        }
    
        ...
    }
    
    
    public class MyAdapter extends BaseAdapter
    {
        ...
    
        @Override
        public View getView(final int position, View convertView, ViewGroup parent)
        {
            View view = convertView;
            if (view == null) 
            {
                LayoutInflater inflater = (LayoutInflater) mFragment.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.listview_item, null);
            }
    
            ...
    
            // handle listview item click
            // this method works pretty well also with checkboxes
            view.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    // do something here
                    // for communication with Fragment/Activity, you can use your own listener
                }
            });
    
            return view;
        }
    
        ...
    }
    

提交回复
热议问题