I am building a custom adapter for a listview - I would like this adapter to give the listview alternating background colours.
boolean alternate = false;
@
I wanted to highlight the solution so people aren't confused.
If you want the colors/image, or whatever alteration done on the listview at draw time you need to set it in the getView like below, but if you want it to show on click you need to do it in an onClick method like below.
@Override
public View getView(int position, View view, ViewGroup parent) {
if(view == null) {
view = inflater.inflate(R.layout.dashboard_item, parent, false);
}
if(selected[position]) {
view.setBackgroundColor(Color.LTGRAY);
} else {
selected[position] = false;
view.setBackgroundColor(Color.WHITE);
}
return view;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//this is just my custom object..you could also assign your boolean here to see if it is "highlighted"
Item o = (Item)listView.getItemAtPosition(position);
if(adapter.selected[position] == true) {
adapter.selected[position] = false;
view.setBackgroundColor(Color.WHITE);
} else {
adapter.selected[position] = true;
view.setBackgroundColor(Color.LTGRAY);
}
}
My boolean check is just a boolean array like
private boolean[] selected;
I initalize it in the my subclass of the ArrayAdapater constructor.
selected = new boolean[objects.size()];
Arrays.fill(selected, Boolean.FALSE);