Saving State of the checkbox in a custom list view with Checkboxes

后端 未结 2 847
旧时难觅i
旧时难觅i 2020-12-05 22:44

I have a list view with checkboxes and I want that when user selects any check box and closes the application, and again opens the application, the same checkboxes should be

相关标签:
2条回答
  • 2020-12-05 22:50

    Declare a boolean array to record the checked state (in the setOnCheckedChangeListener()) for each position item, then call setChecked() after setOnCheckedChangeListener(). Just that simple.

    0 讨论(0)
  • 2020-12-05 22:57

    Your code is almost right. Just need to do some changes...

    Check My code of setOnCheckedChangeListener for checkbox.. I hope it will work

    public class MyCustomBaseAdapter extends BaseAdapter {
        private static ArrayList<SearchResults> searchArrayList;
        ViewHolder holder;
        private LayoutInflater mInflater;
        Editor editor;
        Context context;
    
        public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
            searchArrayList = results;
            mInflater = LayoutInflater.from(context);
        }
    
        public int getCount() {
            return searchArrayList.size();
    
        }
    
        public Object getItem(int position) {
            return searchArrayList.get(position);
        }
    
        public long getItemId(int position) {
            return position;
        }
    
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            SharedPreferences sharedPrefs = context.getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
    
    
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.custom_row_view, null);
                holder = new ViewHolder();
                holder.txtName = (TextView) convertView.findViewById(R.id.name);
                holder.cB = (CheckBox)convertView.findViewById(R.id.cb_category);
    
                convertView.setTag(holder);
            } 
            else {
                holder = (ViewHolder) convertView.getTag();
            }
    
    
            editor = sharedPrefs.edit();
    
            holder.txtName.setText(searchArrayList.get(position).getName());
    
            holder.cB.setChecked(sharedPrefs.getBoolean("CheckValue"+position, false));
           holder.cB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
           editor.putBoolean("CheckValue"+position, isChecked);
           editor.commit();
           }});
            return convertView;
        }
    
    
        static class ViewHolder {
            TextView txtName;
            CheckBox cB;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题