CheckBox gets unchecked on scroll in a custom listview

前端 未结 4 1078
野趣味
野趣味 2020-11-29 12:13

I know that this question has been asked over and over again but still I\'ve not been a able to find a suggestion that really helps me. The checkbox is unchecked whenever th

4条回答
  •  时光说笑
    2020-11-29 12:45

    getView() is called whenever a previously invisible list item needs to be drawn. Since you recreate itemChecked[] each time this method is called you will have the new checkbox unchecked and a different Array for each resulting View. (final in Java does not make that field unique like in C) Simplest way to solve that is to make itemChecked a classmember and set / restore checkbox state based on that one.

    public class MyListAdapter extends ArrayAdapter {
        private final boolean[] mCheckedState;
        private final Context mContext;
    
        public MyListAdapter(Context context, int resource, int textViewResourceId, List objects) {
            super(context, resource, textViewResourceId, objects);
            mCheckedState = new boolean[objects.size()];
            mContext = context;
        }
    
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // simplified to just a Checkbox
            // ViewHolder and OnCheckedChangeListener stuff left out 
            CheckBox result = (CheckBox)convertView;
            if (result == null) {
                result = new CheckBox(mContext);
            }
            result.setChecked(mCheckedState[position]);
            return result;
        }
    }
    
        

    提交回复
    热议问题