StateListDrawable not working

…衆ロ難τιáo~ 提交于 2019-12-03 17:18:44

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