StateListDrawable not working

Charlie-Blake picture Charlie-Blake · Oct 5, 2012 · Viewed 8.7k times · Source

I'm trying to programatically set a StateListDrawable as the background of my custom view for a library project. Here's what I'm doing:

final TypedArray a = getContext().obtainStyledAttributes(attrs,
            R.styleable.ActionBar);
    int firstColor = a.getColor(
            R.styleable.ActionBar_backgroundGradientFirstColor, 0xff000000);
    int secondColor = a
            .getColor(R.styleable.ActionBar_backgroundGradientSecondColor,
                    0xff000000);
    int textViewColor = a.getColor(R.styleable.ActionBar_titleColor,
            0xffffffff);
    int onClickColor = a.getColor(
            R.styleable.ActionBar_backgroundClickedColor, 0xff999999);
    a.recycle();

    StateListDrawable sld = new StateListDrawable();
    GradientDrawable drawable = new GradientDrawable(
            Orientation.TOP_BOTTOM, new int[] { firstColor, secondColor });
    sld.addState(new int[] { android.R.attr.state_enabled },
            new ColorDrawable(onClickColor));
    sld.addState(new int[] { android.R.attr.state_pressed }, drawable);

    action2.setBackgroundDrawable(sld);
    action3.setBackgroundDrawable(sld);
    actionBack.setBackgroundDrawable(sld);
    pb.setBackgroundDrawable(drawable);
    tv.setBackgroundDrawable(drawable);
    tv.setTextColor(textViewColor);

However, this is not working: It always draws the enabled state. I want it to draw the Pressed state when I press the button. What am I doing wrong?

Answer

Hendrik picture Hendrik · Oct 5, 2012

I guess the button is still enabled while it's pressed?

You could try reversing the order:

sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(new int[] { android.R.attr.state_enabled },
        new ColorDrawable(onClickColor));

Probably the first currently valid state is being drawn.

If you want a different background when it's being pressed and another background for all other cases you can also use:

sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(new int[] { StateSet.WILD_CARD },
        new ColorDrawable(onClickColor));

Addition: I just tested this and the following test code works for me:

Button testButton = new Button(context);
            testButton.setText("Test");
            StateListDrawable sld = new StateListDrawable();
            GradientDrawable drawable = new GradientDrawable(
                    Orientation.TOP_BOTTOM, new int[] { Color.BLUE, Color.RED });
            sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
            sld.addState(StateSet.WILD_CARD, new ColorDrawable(Color.YELLOW));
            testButton.setBackgroundDrawable(sld);          
            mainLayout.addView(testButton);