Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android listview item not showing selected color

I have this list view:

<ListView
            android:id="@+id/contactsView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/searchButton"
            android:divider="@color/DarkGoldenrod"
            android:dividerHeight="0.1dp"
            android:listSelector="@drawable/list_selector"
            android:choiceMode="singleChoice" />

This is the code for the list_selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@android:drawable/myRedColor" android:state_pressed="true"/>
    <item android:drawable="@android:drawable/myBlueColor" android:state_selected="true"/>
    <item android:drawable="@android:drawable/myGreenColor"/>

</selector>

In my main activity class I have put the following:

contactsView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                arg1.setSelected(true);
                selectedContactIndex = (int) arg3;
            }
        });

contactsView is the list view, and I have confirmed that it IS being selected but the color is not staying. I click it and it changes then changes back. Any idea why?

like image 320
Ogen Avatar asked Oct 05 '13 01:10

Ogen


2 Answers

Instead of android:listSelector="@drawable/list_selector" in ListView use it as background in row.xml

like image 58
Richa Avatar answered Nov 12 '22 22:11

Richa


You can do on this way also on the layout in which u have your listview set the background of the layout

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

And then in your activity

ListView.setSelector(R.drawable.list_selector);
like image 33
Developer Avatar answered Nov 12 '22 22:11

Developer