Reputation: 389
My listview has a button per line. When clicked I change this line color. The problem is while scrolling it... return to default or other lines are colored.
The button listening is coded inside the adapter
public CustomAdapter(Context context, List<Map<String, String>> items, int resource, String[] from, int[] to) {
super(context, items, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
final View line = view;
TextView txtid = (TextView) view.findViewById(R.id.txtid);
TextView txtnumber = (TextView) view.findViewById(R.id.txtnumber);
Button btn = (Button) view.findViewById(R.id.btncheck);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (txtnumber.getText().toString().equals(KEY-CODE)){
line.setBackgroundColor(0x7F00FF00);
}else {
line.setBackgroundColor(0x7FFF0000);
}
}
});
return view;
}
Upvotes: 0
Views: 42
Reputation: 4888
I faced somthing like this once, you can save the state of the button using HashMap where the the boolean indicate the state of the button ( true if it was clicked and false otherwhise ), know inside getItemView check if current button is clicked or not from the HashMap.
A little bit of code :
inside getItemView first initialize each button to false (not clicked)
if(map.get(v.findViewById(R.id.button)) == null)
map.put(v.findViewById(R.id.button)),false);
and after clicking the button set the Boolean to true :
map.put(v.findViewById(R.id.button)),true);
and finally check if the Boolean is set to true or false and set the color.
Upvotes: 1