Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android listview item background change

i have a android listview. i want to change listview item background when i click one listview item.

and then previous selected item must go back to default background. this means only one item has to be selected.

i have searched it for a long time. i can change background of selected item using onItemClick()

but i can't change previous selected item. for example, if i select second item, it was changed. and then i select third item. oh my god! it is changed too! what can i do for this. how can i get the previous position?

here is my android code.

private class ListViewItemClickListener implements
            AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {

            TextView title = (TextView) view.findViewById(R.id.title);
            title.setBackgroundResource(R.drawable.list_shape);

        }
    }
like image 692
Moon Taejin Avatar asked Nov 13 '13 12:11

Moon Taejin


1 Answers

You should use the built in methods of selecting items in a listview. Manually changing the background is prone to error as you have found.

Add this attribute to the root view in your listview item xml

android:background="?android:attr/activatedBackgroundIndicator"

then call setItemChecked(x, true) on your ListView where x is the position of the item you want to be selected.

Ensure your listview has a ChoiceMode set that allows selection (such as "SingleChoice")

like image 117
Kuffs Avatar answered Oct 14 '22 14:10

Kuffs