0

There are some similar questions. But they are not resolved!

Set RippleDrawable corner radius programmatically

I know that this behaviour can be done using xml file. But I must it programmatically.

My code is below:

    GradientDrawable gd = new GradientDrawable();
    gd.setColor(Color.YELLOW);
    gd.setStroke(2, Color.RED);
    gd.setCornerRadius(45.0f);
    view.setBackground(gd);

    int[] colors = new int[]{Color.GRAY};
    int[][] states = new int[][]{ new int[]{}};
    ColorStateList stateList = new ColorStateList(states, colors);

    Drawable mask = getResources().getDrawable(R.drawable.icon1);
    RippleDrawable rippleDrawableBackgorund = new RippleDrawable(stateList, view.getBackground(), mask);

    view.setBackground(rippleDrawableBackgorund);

Screenshot is below for pressed state:

enter image description here

How can I set borderRadius for RippleDrawable? Also, rippleDrawableBackgorund.setRadius changes this effect for hover state.

enter image description here

us2956
  • 476
  • 12
  • 27
  • Kind of duplicate of https://stackoverflow.com/questions/35388949/ripple-effect-over-the-actual-border. It seems you can't provide a corner radius but may provide a *mask* to restrict the ripple's shape: ["At run time, a single layer may be set as the mask using setId(..., android.R.id.mask) or an existing mask layer may be replaced using setDrawableByLayerId(android.R.id.mask, ...). "](https://developer.android.com/reference/android/graphics/drawable/RippleDrawable). – JimmyB Nov 15 '18 at 11:22
  • 1
    Not duplicate. I want to create programmatically not xml. – us2956 Nov 15 '18 at 11:28
  • 2
    But you can set up the drawable in the same way, through similarly named methods, as in the XML. – JimmyB Nov 15 '18 at 11:30

1 Answers1

3

This guide is save my hours :) http://blog.blundellapps.co.uk/tut-programmatically-create-a-rippledrawable-of-any-color/

Use mask parameter of RippleDrawable constructor.

private static Drawable getRippleColor(int color) {
    float[] outerRadii = new float[8];
    Arrays.fill(outerRadii, 3);
    RoundRectShape r = new RoundRectShape(outerRadii, null, null);
    ShapeDrawable shapeDrawable = new ShapeDrawable(r);
    shapeDrawable.getPaint().setColor(color);
    return shapeDrawable;
}
us2956
  • 476
  • 12
  • 27