ListView items are not marked when pressed
I'm implementing an Android activity. I a开发者_开发技巧m using a ListView in my application layout, and setting the views colors by setBackgroundResource in my inherited SimpleAdapter getView.
public class SpecialAdapter extends SimpleAdapter {
public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
super(context, items, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (mSensorsStatus[position].equals(mSensorStatus[SENSOR_STATUS_ALERT])) {
view.setBackgroundResource(R.color.red);
}
else if (mSensorsStatus[position].equals(mSensorStatus[SENSOR_STATUS_ARMED])) {
view.setBackgroundResource(R.color.light_grey);
}
return view;
}
}
My problem is that when I click one of the items, it is not colored in yellow/orange as it usually does (when removing the setBackgroundResource it works fine)
Some more info: I tried to set the background color by mListView.getChildAt(index).setBackgroundResource(R.color.red) instead of the getView implementation, and the result was the same.
appreciate your help
That is because you called setBackgroundResource()
and set the background to a color. If you want list selection to work, either do not call setBackgroundResource()
, or set the background resource to a suitable StateListDrawable
that has the selector and all other necessary states.
A LayerList drawable could match your desired behaviour as described here: ListView item with list_selector_background as LayerList drawable
精彩评论