Skip to content

Instantly share code, notes, and snippets.

@samuel22gj
Last active December 14, 2016 07:16
Show Gist options
  • Select an option

  • Save samuel22gj/ce0f8897f54eb5c35aeb5eec03cd5629 to your computer and use it in GitHub Desktop.

Select an option

Save samuel22gj/ce0f8897f54eb5c35aeb5eec03cd5629 to your computer and use it in GitHub Desktop.
public class RippleDrawableCompat {
public static class Builder {
int normalColor = Color.TRANSPARENT;
int pressColor = Color.TRANSPARENT;
int strokeColor = Color.TRANSPARENT;
int strokeWidth = 0;
float radius = 0.0f;
public Builder() {
}
public Builder normalColor(int normalColor) {
this.normalColor = normalColor;
return this;
}
public Builder pressColor(int pressColor) {
this.pressColor = pressColor;
return this;
}
public Builder strokeColor(int strokeColor) {
this.strokeColor = strokeColor;
return this;
}
public Builder strokeWidth(int strokeWidth) {
this.strokeWidth = strokeWidth;
return this;
}
public Builder radius(float radius) {
this.radius = radius;
return this;
}
public Drawable build() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return createRippleDrawable(normalColor, pressColor, strokeColor, strokeWidth, radius);
} else {
return createStateListDrawable(normalColor, pressColor, strokeColor, strokeWidth, radius);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static Drawable createRippleDrawable(@ColorInt int normalColor, @ColorInt int pressColor, @ColorInt int strokeColor, int strokeWidth, float radius) {
Drawable content = createGradientDrawable(normalColor, strokeColor, strokeWidth, radius);
Drawable mask = createShapeDrawable(radius);
return new RippleDrawable(ColorStateList.valueOf(pressColor), content, mask);
}
private static Drawable createStateListDrawable(@ColorInt int normalColor, @ColorInt int pressColor, @ColorInt int strokeColor, int strokeWidth, float radius) {
Drawable normal = createGradientDrawable(normalColor, strokeColor, strokeWidth, radius);
Drawable press = createGradientDrawable(pressColor, strokeColor, strokeWidth, radius);
StateListDrawable drawable = new StateListDrawable();
drawable.addState(new int[]{android.R.attr.state_pressed}, press);
drawable.addState(new int[]{}, normal);
return drawable;
}
private static Drawable createGradientDrawable(@ColorInt int solidColor, @ColorInt int strokeColor, int strokeWidth, float radius) {
GradientDrawable drawable = new GradientDrawable();
drawable.setColor(solidColor);
drawable.setStroke(strokeWidth, strokeColor);
drawable.setCornerRadius(radius);
return drawable;
}
private static Drawable createShapeDrawable(float radius) {
float[] outerRadii = new float[8];
Arrays.fill(outerRadii, radius);
RoundRectShape roundRectShape = new RoundRectShape(outerRadii, null, null);
return new ShapeDrawable(roundRectShape);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment