Listview with custom adapter containing CheckBoxes

后端 未结 3 875
借酒劲吻你
借酒劲吻你 2020-12-05 12:17

I have a ListView which uses a custom adapter as shown:

private class CBAdapter extends BaseAdapter implements OnCheckedChangeListener{

    Context context;         


        
3条回答
  •  时光说笑
    2020-12-05 12:49

    This may not be the most elegant or efficient solution but it works for my situation. For some reason attempting to reuse the views either from an array of views or using convertView makes every thing go wobbley and the CheckBoxes fail to respond.

    The only thing that worked was creating a new View everytime getView() is called.

        public View getView(final int position, View convertView, ViewGroup parent) {
            LinearLayout view;
            view=(LinearLayout)inflater.inflate(R.layout.record_view_start,null);
    
    
            TextView tv=(TextView)view.findViewById(R.id.engName);
            tv.setText(englishNames[position]);
    
            CheckBox cBox=(CheckBox)view.findViewById(R.id.checkBox1);
            cBox.setChecked(checked[position]);
            cBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    checked[position]=isChecked;
                }
            });
            return view;
        }
    

    Finding this solution was also hampered by the fact that I was calling a separately defined onCheckedChangedListener, that then identified which CheckBox by id, rather than having a new listener for each CheckBox.

    As yet I haven't marked this as the correct answer as I'm hoping that others may have some input regarding the rather wasteful rebuilding the view every time.

提交回复
热议问题