Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does calling setBackgroundColor on a view break its long click color change and highlighting?

In Android, by default when you long click on a list item, it goes from the highlight color to white indicating that the user has held it down and a context item will be displayed. Also, you can use the trackball (or arrow buttons on some phones) to select list items rather then using your fingers.

However, I have a ListView whose item's views I am calling setBackgroundColor on, and both of those expected behaviors no longer work. Anybody know why this is and how to fix it?

Notes: Setting the background color in the xml is not an option because I need to be able to set/change the color dynamically.

The code for my newView function is as follows:

@Override
public View newView(Context ctx, Cursor cursor, ViewGroup parent)
{
    View view = new View(mCtx);
    final LayoutInflater li = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = li.inflate(R.layout.task_list_item, null);

    return view;
}
like image 487
finiteloop Avatar asked Dec 03 '22 01:12

finiteloop


1 Answers

By default, ListView has a Selector that will play a TransitionDrawable when you longpress a list item. However, if your list item view has a solid background, then you won't be able to see the selector's longpress animation (or on any other states) , because it's covered up by the list item's background.

If you want to see the selector's longpress animation/selected/pressed state, then the list item's has to have a transparent background when the item is selected/pressed/longpressed. You can do it by using a StateListDrawable as your item's background instead of a solid color.

Here is a sample of StateListDrawable for that purpose:

public class ColorfulListItemDrawable extends StateListDrawable {
    private final PaintDrawable mColor;

    public ColorfulListItemDrawable(int color) {
        mColor = new PaintDrawable(color);
        initialize();
    }
    private void initialize() {
        Drawable color = mColor;
        Drawable selected = new ColorDrawable(Color.TRANSPARENT);
        addState(new int[] {android.R.attr.state_pressed, android.R.attr.state_enabled, 
                android.R.attr.state_window_focused}, selected);
        addState(new int[] {android.R.attr.state_pressed, android.R.attr.state_enabled, 
                android.R.attr.state_window_focused,android.R.attr.state_selected}, selected);
        addState(new int[] {android.R.attr.state_enabled,android.R.attr.state_window_focused, android.R.attr.state_selected}, selected);
        addState(new int[] {}, color);
    }
    public void setColor(int color) {
        mColor.getPaint().setColor(color);
        mColor.invalidateSelf();
    }   
}
like image 57
Ricky Lee Avatar answered Dec 28 '22 11:12

Ricky Lee