How to use RippleDrawable programmatically in code (not xml) with Android 5.0 Lollipop?

前端 未结 3 446
我在风中等你
我在风中等你 2020-12-13 04:32

I have the following code for my ripple:




        
3条回答
  •  無奈伤痛
    2020-12-13 05:01

    public static Drawable getAdaptiveRippleDrawable(
        int normalColor, int pressedColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new RippleDrawable(ColorStateList.valueOf(pressedColor),
                    null, getRippleMask(normalColor));
        } else {
            return getStateListDrawable(normalColor, pressedColor);
        }
    }
    
    private static Drawable getRippleMask(int color) {
        float[] outerRadii = new float[8];
        // 3 is radius of final ripple, 
        // instead of 3 you can give required final radius
        Arrays.fill(outerRadii, 3);
    
        RoundRectShape r = new RoundRectShape(outerRadii, null, null);
        ShapeDrawable shapeDrawable = new ShapeDrawable(r);
        shapeDrawable.getPaint().setColor(color);
        return shapeDrawable;
    }
    
    public static StateListDrawable getStateListDrawable(
        int normalColor, int pressedColor) {
        StateListDrawable states = new StateListDrawable();
        states.addState(new int[]{android.R.attr.state_pressed}, 
            new ColorDrawable(pressedColor));
        states.addState(new int[]{android.R.attr.state_focused}, 
            new ColorDrawable(pressedColor));
        states.addState(new int[]{android.R.attr.state_activated}, 
            new ColorDrawable(pressedColor));
        states.addState(new int[]{}, 
            new ColorDrawable(normalColor));
        return states;
    }
    

    You can get the drawable and apply to any view using view.setDrawable.
    For Lollipop+ devices you will get ripple else it will change the color of view.

提交回复
热议问题