Android StateListDrawable的坑

有问题的代码:

        StateListDrawable background = new StateListDrawable();
        CircleDrawable pressedDrawable = new CircleDrawable(PluginRely.getColor(R.color.button_pressed));
        CircleDrawable drawable = new CircleDrawable(PluginRely.getColor(R.color.button_unpressed));
        background.addState(new int[]{android.R.attr.state_pressed},pressedDrawable);
        background.addState(new int[]{}, drawable);
        mIvPlay.setBackgroundDrawable(background);
        mIvPlayStop.setBackgroundDrawable(background);

没问题的代码:

        StateListDrawable background = new StateListDrawable();
        StateListDrawable background2 = new StateListDrawable();
        CircleDrawable pressedDrawable = new CircleDrawable(PluginRely.getColor(R.color.button_pressed));
        CircleDrawable drawable = new CircleDrawable(PluginRely.getColor(R.color.button_unpressed));
        background.addState(new int[]{android.R.attr.state_pressed},pressedDrawable);
        background.addState(new int[]{}, drawable);

        background2.addState(new int[]{android.R.attr.state_pressed},pressedDrawable);
        background2.addState(new int[]{}, drawable);
        mIvPlay.setBackgroundDrawable(background);
        mIvPlayStop.setBackgroundDrawable(background2);

有问题的代码,会导致,mIvPlay mIvPlayStop 两个ImageView 的点击状态混乱,明明不是按下态,却显示的是按下态的图片。所以,不要省事。两个ImageView 在代码里面,不可以公用同一个StateListDrawable 对象!

原文地址:https://www.cnblogs.com/caoxinyu/p/10568528.html