I'm trying to dynamically update (change color and strikethrough text) a TextView within a ListView when the user checks a CheckBox.
My code works somewhat but for some reason only on the second click of the checkbox i.e. user checks nothing happens, user un-checks and checks a second time TextView then updates as required?
Any help appreciated.
my code:
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.shoppinglist, parent, false);
}
String anItem = get_Item(position);//from item array
((TextView) view.findViewById(R.id.tvSLItemName)).setText(anItem);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.cbBoxSL);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
View aView = convertView;
if (aView == null) {
aView = lInflater.inflate(R.layout.shoppinglist, parent, false);
}
if(isChecked){
checked[position] = true;
((TextView) aView.findViewById(R.id.tvSLItemName)).setTextColor(Color.GRAY);
((TextView) aView.findViewById(R.id.tvSLItemName)).setPaintFlags(
((TextView) aView.findViewById(R.id.tvSLItemName)).getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
//aView.invalidate();
notifyDataSetChanged();
}
else{
checked[position] = false;
}
}
});
checkBox.setChecked(checked[position]);
return view;
}
Updated code as suggested below:
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.shoppinglist, parent, false);
}
String anItem = get_Item(position);//from item array
((TextView) view.findViewById(R.id.tvSLItemName)).setText(anItem);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.cbBoxSL);
checkBox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
View aView = convertView;
if (aView == null) {
aView = lInflater.inflate(R.layout.shoppinglist, parent, false);
}
if(((CheckBox) v).isChecked()) {
checked[position] = true;
((TextView) aView.findViewById(R.id.tvSLItemName)).setTextColor(Color.GRAY);
((TextView) aView.findViewById(R.id.tvSLItemName)).setPaintFlags(
((TextView) aView.findViewById(R.id.tvSLItemName)).getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//aView.invalidate();
notifyDataSetChanged();
}else{
checked[position] = false;
}
}
});
checkBox.setChecked(checked[position]);
return view;
}
No change to problem statement.