0

I'm implementing an Android activity. I am 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

Zvi
  • 63
  • 1
  • 6

2 Answers2

1

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • The problem is that I need to have at least 5 different possible colors to the items (the code I sent is partial, there are more conditions and colors in the getView). So how can I color each Item with a wanted color without using setBackgroundResource? StateListDrawable has this flexibility? – Zvi Feb 23 '11 at 13:13
  • @Zvi: You will probably need five resources, one per color, each a `StateListDrawable`. I *strongly* encourage you to reconsider your straetgy of changing background colors this way, as your UI model will work poorly on Android, particularly Android 3.0. Change the color of something else (e.g., a colored bar down one side). – CommonsWare Feb 23 '11 at 13:27
  • I am trying to use the `StateListDrawable` with `LevelListDrawable` so that I will have support to more than one color. I'll update with the results shortly – Zvi Feb 23 '11 at 13:46
  • Can I use `StateListDrawable` with a color and not with a png file? – Zvi Feb 23 '11 at 14:40
0

A LayerList drawable could match your desired behaviour as described here: ListView item with list_selector_background as LayerList drawable

Community
  • 1
  • 1
Diego Frehner
  • 2,396
  • 1
  • 28
  • 35