StateListDrawable not working

自古美人都是妖i 提交于 2019-12-21 06:19:23

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/12745968/statelistdrawable-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!