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
Declare a boolean array to record the checked state (in the setOnCheckedChangeListener()
) for each position item, then call setChecked()
after setOnCheckedChangeListener()
. Just that simple.
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;
}
}