重写以符合新方法,摆脱弃用的方法

时间:2016-06-30 15:59:28

标签: android android-studio deprecated

我无法理解如何重写下面的类,以便它不再使用已弃用的代码。这是我的完整课程。

import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.widget.Button;

public class BgButtonStyle extends Button {

    public BgButtonStyle(Context context) {
        super(context);
    }

    public BgButtonStyle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BgButtonStyle(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setBackgroundDrawable(Drawable d) {
        // Replace the original background drawable (e.g. image) with a LayerDrawable that
        // contains the original drawable.
        BgButtonStyleBackgroundDrawable layer = new BgButtonStyleBackgroundDrawable(d);
        super.setBackgroundDrawable(layer);
    }

    /**
     * The stateful LayerDrawable used by this button.
     */
    protected class BgButtonStyleBackgroundDrawable extends LayerDrawable {
        // The color filter to apply when the button is pressed
        protected ColorFilter _pressedFilter = new LightingColorFilter(Color.LTGRAY, 1);
        // Alpha value when the button is disabled
        protected int _disabledAlpha = 100;

        public BgButtonStyleBackgroundDrawable(Drawable d) {
            super(new Drawable[]{d});
        }

        @Override
        protected boolean onStateChange(int[] states) {
            boolean enabled = false;
            boolean pressed = false;

            for (int state : states) {
                if (state == android.R.attr.state_enabled)
                    enabled = true;
                else if (state == android.R.attr.state_pressed)
                    pressed = true;
            }

            mutate();
            if (enabled && pressed) {
                setColorFilter(_pressedFilter);
            } else if (!enabled) {
                setColorFilter(null);
                setAlpha(_disabledAlpha);
            } else {
                setColorFilter(null);
            }

            invalidateSelf();

            return super.onStateChange(states);
        }

        @Override
        public boolean isStateful() {
            return true;
        }
    }
}

我将这个类用于按钮,这样无论按钮的背景颜色是什么,它都会应用一个过滤器,允许我在按下按钮时看到onPressed效果。

我不确定如何从已弃用的setBackgroundDrawable和LayerDrawable

更新它

1 个答案:

答案 0 :(得分:0)

没关系,我是个白痴。我只是用setBackground替换了setBackgroundDrawable方法。一切都按预期进行。