I am trying to use a selector
to highlight a selected row in my ListView
. I need it to remain highlighted after i have released the press. Symbolizing the highlighted row is the row selected.
Currently the text changes color by default. I need to change the background color.
I have the ListView
in a fragment that is inside of a DrawerLayout
. When i select a device, the DrawerLayout
closes. When i open the DrawerLayout
again, the background of the device i selected is not changed. The text of the device selected is a different color, but not the background.
I have tried numerous suggestions here on SO and have found nothing that works. I am targeting API-17 and minsdk is API-17.
Here are some posts i have tried with no success.
- ListView Item Selected State not working
- Change background color of selected item on a ListView
- Android ListView selected item stay highlighted
Let me know if you need any further details, thanks.
Here is my code(with the last thing i tried):
device_list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/device_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:background="@drawable/device_selector" >
</ListView>
device_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_activated="true"
android:drawable="@drawable/device_selected"/>
<item
android:drawable="@drawable/device_not_selected"/>
</selector>
strings.xml
<drawable name="device_selected">#777777</drawable>
<drawable name="device_not_selected">#555555</drawable>
DeviceListFragment
public class DeviceListFragment extends Fragment implements OnItemClickListener {
public View onCreateView(...) {
View view = inflater.inflate(R.layout.device_list_fragment, container, false);
this.devicesArrayAdapter = new DevicesArrayAdapter(this.getActivity());
this.deviceListView = (ListView) view.findViewById(R.id.device_list_view);
this.deviceListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
this.deviceListView.setAdapter(this.devicesArrayAdapter);
this.deviceListView.setOnItemClickListener(this);
return view;
}
public void onItemClick(...) {
this.deviceListView.setItemChecked(position, true);
}
}
DevicesArrayAdapter
public class DevicesArrayAdapter extends ArrayAdapter<Device> {
public View getView(...) {
View rowView = layoutInflater.inflate(R.layout.device_element, parent, false);
return rowView;
}
}