tags:

views:

80

answers:

1

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 the selection the background of the view should change. but now when i select one item, the item does get selected but the back ground of random listitems changes at the same time, but the selection is still correct please tell me where im 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);
    }

}
A: 

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.

antonyt