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

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

I have the following code for my ripple:




        
3条回答
  •  我在风中等你
    2020-12-13 04:47

    This is how I was able to achieve this.

    Note that this is Api 21+ only so you will have to fallback to a normal Drawable if you support lower versions.

    public static RippleDrawable getPressedColorRippleDrawable(int normalColor, int pressedColor)
    {
        return new RippleDrawable(getPressedColorSelector(normalColor, pressedColor), getColorDrawableFromColor(normalColor), null);
    }
    
    public static ColorStateList getPressedColorSelector(int normalColor, int pressedColor)
    {
        return new ColorStateList(
            new int[][]
                {
                    new int[]{android.R.attr.state_pressed},
                    new int[]{android.R.attr.state_focused},
                    new int[]{android.R.attr.state_activated},
                    new int[]{}
                },
            new int[]
                {
                    pressedColor,
                    pressedColor,
                    pressedColor,
                    normalColor
                }
        );
    }
    
    public static ColorDrawable getColorDrawableFromColor(int color)
    {
        return new ColorDrawable(color);
    }
    

    Edit: I tinkered with this some more and discovered that the ColorStateList doesn't need to be nearly as complex as the above solution. I have simplified it to the below snippet. (Everything else in the above code block is the same. I only changed the ColorStateList creation.) I will leave the above block as the original, in case this method doesn't work for someone.

    new ColorStateList(
        new int[][]
            {
                new int[]{}
            },
        new int[]
            {
                pressedColor
            }
    );
    

提交回复
热议问题