Pregunta

I´m using SimpleAdapter in my ListActivity and I want when user select an item highlight this item. I tried extends SimpleAdapter and override getView() method:

        public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        if (position == mItemIndex) {

           convertView.setSelected(true);
           convertView.setPressed(true);
           convertView.setBackgroundColor(Color.parseColor("#FF9912"));

        }
        return view;
        }

but this solution don´t work properly. It set background color to more then one list row. Can sameone help me?

¿Fue útil?

Solución

That's because the convertView is being reused and you do not update the selected state for both cases (selected / not selected). You need to call setSelected(false) when it is not the item you want selected and reset the background color. Also, the call to setPressed is not needed.

You also should checkout the ColorStateList which will allow you to define the colors for various states. Then you could just use the built in support for single item selection.

Otros consejos

So instead of (e.g.) opening a new Activity you want to highlight the selected list item by changing its colors if the user clicks on it?

In your ListActivity you need to override onListItemClick()

@Override
protected void onListItemClick(ListView list, View view, int position, long id) {
    super.onListItemClick(list, view, position, id);

    TextView tv = (TextView)view;
    tv.setTextColor(Color.RED);
    tv.setBackgroundColor(Color.BLUE);
}

This changes the color of the selected entry to red (text) and blue (background). Thats the first step. But the first clicked entry stays this way, even if you click another one. So you need to change that (somehow).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top