Android list activity
OK, I have a list activity in my application. I have tried to make it so that when a list item is selected to show开发者_StackOverflow社区 the selection the background of the view should change. But now when I select one item, the item does get selected, but the background of random list items changes at the same time, but the selection is still correct. Where am I making the mistake?
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Cursor c = (Cursor) mAdapter.getItem(position);
String a = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String b = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (names != null)
{
if(numbers.contains(b))
{
names = names.replace(a+";", "");
numbers = numbers.replace(b+";", "");
v.setBackgroundResource(R.drawable.background);
}
else{
names = names + a + ";";
numbers = numbers + b + ";";
v.setBackgroundResource(R.drawable.background_sel);
}
}
else
{
names = a+";";
numbers = b+";";
v.setBackgroundResource(R.drawable.background_sel);
}
}
I believe Android can reuse the same views to create your list; this is why when you set the background for one view you can see other list elements have the new colour also.
To get the behaviour you want, you should remember/restore the 'selected' state in the same place where the ListView is getting the data to populate the list. You will probably have to create your own ListAdapter and override getView()
to set the background on a per-item (as opposed to per-view-object) basis.
精彩评论