In my application's list view I have a checkBox in every listItem.I am using this code for it in the custom BaseAdapter -
public class QuestionAdapter extends BaseAdapter {
private Context context;
private ArrayList<QuestionItem> questionItems;
public QuestionAdapter(Context context, ArrayList<QuestionItem> questionItems){
this.context = context;
this.questionItems = questionItems;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MySQLiteHelper sqliteHelper = new MySQLiteHelper(context);
QuestionViewHolder holder = null;
OnCheckedChangeListener mStarCheckedChanceChangeListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final String id = (String) buttonView.getTag();
Log.v(TAG, "isChecked is " + isChecked);
Log.v(TAG,"id is " + id);
}
};
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.question_list_item, null);
holder = new QuestionViewHolder();
holder.qid = (TextView) convertView.findViewById(R.id.qid);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.star = (CheckBox) convertView.findViewById(R.id.btn_star);
convertView.setTag(holder);
}
else{
holder = (QuestionViewHolder) convertView.getTag();
}
holder.qid.setText(questionItems.get(position).getQid());
holder.title.setText(questionItems.get(position).getTitle());
holder.star.setTag(questionItems.get(position).getQid());
if(sqliteHelper.questionexists(questionItems.get(position).getQid())){
holder.star.setOnCheckedChangeListener(null);
holder.star.setChecked(true);
holder.star.setOnCheckedChangeListener(mStarCheckedChanceChangeListener);
}
else{
holder.star.setOnCheckedChangeListener(null);
holder.star.setChecked(false);
holder.star.setOnCheckedChangeListener(mStarCheckedChanceChangeListener);
}
//star.setChecked(false);
return convertView;
}
Star CheckBox's onCheckedChangeListener works fine if manually I select and unselect it.However if I select it and scroll down the listview and then again scroll up,the state of checkBox changes from selected to unselected.
How to retain the state of a checkbox?Please point me if I am missing something very trivial or very important.
Hope this following link will help you.
http://lalit3686.blogspot.in/2012/06/today-i-am-going-to-show-how-to-deal.html