setSelection not working - getSelectedItemPosition always returns -1

Viewed 1657

I have implemented a Navigation Drawer. Everything is working fine except I can't change background of the item on selected state. The background is changed when pressed, but returns back to normal when released.

In my xml, I set both state_pressed and state_selected as color2, whereas normal is color1. I get color2 when pressed but back to color1 when released.

So, I checked my class to find where it went wrong, and saw that getSelectedItemPosition() always returns -1, though position returns correctly (explained below).

Any help please?

EDIT 1: Okay, I added getCheckedItemPosition() method as well, which returns correctly position correctly. But my listview background is not changed, though I used state_checked.

Log.d("postion",""+position);  // THIS RETURNS AS EXPECTED, LET SAY 2 FOR 3RD ITEM
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
Log.d("Selected",""+mDrawerList.getSelectedItemPosition()); // THIS ALWAYS RETURNS -1
Log.d("Checked",""+mDrawerList.getCheckedItemPosition()); // THIS RETURNS CORRECTLY, e.g. 2

LISTVIEW:

<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/col3"
android:dividerHeight="1dp"       
android:listSelector="@drawable/menu_selector"
android:background="@color/col3"/>

MENU_SELECTOR:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/menu_active" />

    <item android:state_selected="true" android:drawable="@drawable/menu_active" />

    <item android:state_checked="true" android:drawable="@drawable/menu_active" />

    <item android:drawable="@drawable/menu_norm" />
</selector>

LIST ITEM

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="@drawable/menu_selector">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="25dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:contentDescription="@string/desc_list_item_icon"
        android:src="@drawable/ic_home"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_toRightOf="@id/icon"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="@color/white"
        android:gravity="center_vertical"
        android:paddingRight="40dp"/>
</RelativeLayout>
3 Answers
Related