Arash GM
Arash GM

Reputation: 10395

ListFragment Selected Item

i have a ListView on a ListFragment that use SimpleCursorAdapter to generate my list. i wanted to highlight selected item in my ListView, i've tried :

v.setBackgroundResource(R.color.listselect_light_blue);

in onListItemClick but it works odd and it selects two row when i click one of items and i want it to be single , i also set Choice Mode

<ListView android:id="@id/android:list"
           android:layout_width="fill_parent"
           android:layout_height="fill_parent" 
           android:choiceMode="singleChoice"   
           android:cacheColorHint="#00000000"
            />

i've tried ListSelector but when i click on an item it doesn't highlight until i scroll the list and it turn highlighted.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    getListView().setSelector(R.drawable.listview_selector);

}

and :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:drawable="@color/listselect_light_blue" />
</selector>

any help would be appreciated

Upvotes: 3

Views: 7551

Answers (1)

Dixit Patel
Dixit Patel

Reputation: 3192

Try this way if you want to highlight selected item in Listview.

This works for me.

First set Adapter in Listfragment before use setSelector(..).

 setListAdapter(mAdapter);
 getListView().setSelector(R.drawable.fragment_listselector);      

fragment_listselector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"
        android:exitFadeDuration="@android:integer/config_mediumAnimTime">
    <item android:state_activated="true"
            android:drawable="@drawable/list_item_active_pattern"  />
    <item  android:drawable="@drawable/list_bg_pattern" />
</selector>

when onItemClick(..) is called put this code.

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
    {   
            getListView().setItemChecked(position, true);
            getListView().setSelection(position);
            getListView().setSelected(true);

    }

Upvotes: 5

Related Questions