Set RippleDrawable corner radius programmatically

馋奶兔 提交于 2020-01-03 17:04:22

问题


I create a RippleDrawable like below. But I can't change the corner radius of the RippleDrawable. It doesn't have a method like setCornerRadii(float[] f).

public static RippleDrawable getPressedColorRippleDrawable(int normalColor, int pressedColor) {
    if (Build.VERSION.SDK_INT>=21) {
        RippleDrawable rippleDrawable = new RippleDrawable(getPressedColorSelector(normalColor, pressedColor), getColorDrawableFromColor(normalColor), null);
        //rippleDrawable.setRadius((int) Manager.convertDpToPixel(5));
        return rippleDrawable;
    }
    else
        return null;
}

And the other functions are

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);
}

How can I do it?


回答1:


I was facing the same issue as you: how to set a corner radius to a RippleDrawable.

A simple manner to proceed is to use a GradientDrawable. You can set a radius with setCornerRadius and then pass the configured instance as the second parameter of the RippleDrawable constructor.

Here is an example:

ColorStateList pressedStates = ColorStateList.valueOf(Color.BLUE);

GradientDrawable contentDrawable = new GradientDrawable();
contentDrawable.setColor(Color.WHITE);
contentDrawable.setCornerRadius(16);

RippleDrawable rippleDrawable = new RippleDrawable(pressedStates, contentDrawable, null);
container.setBackground(rippleDrawable);


来源:https://stackoverflow.com/questions/44245757/set-rippledrawable-corner-radius-programmatically

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