ListFragment Selected Item

I have a ListView in a ListFragment that uses a SimpleCursorAdapter to create my list. i wanted to highlight the selected item in my ListView, i tried:

v.setBackgroundResource(R.color.listselect_light_blue);

      

in onListItemClick but it works odd and it selects two rows when I click one of the items and I want it to be single, I also set the selection mode

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

      

I tried ListSelector, but when I click on an item it doesn't highlight until I scroll through the list and turn on.

@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

+3


source to share


1 answer


Try this method if you want to highlight the selected item in Listview

.

This works for me.

First set the Adapter to Listfragment before using 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);

    }

      

+5


source







All Articles