问题
I have the ripple xml. But I am not sure how to get same effect in Java.
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/blue_1"
/>
I would like to define / create / load a ripple, or even set a color in Java. That means, in java, I can load the XML ripple, then assign a color. or can i do do everything in java: Ripple = new Ripple ?
I tried the code from this link: https://github.com/romainguy/google-io-2014/blob/master/app/src/main/java/com/example/android/io2014/DetailActivity.java.
There's a method called colorRipple.
private void colorRipple(int id, int bgColor, int tintColor) {
View buttonView = findViewById(id);
RippleDrawable ripple = (RippleDrawable) buttonView.getBackground();
GradientDrawable rippleBackground = (GradientDrawable) ripple.getDrawable(0);
rippleBackground.setColor(bgColor);
ripple.setColor(ColorStateList.valueOf(tintColor));
}
I tried the code above but it give me NPE.
回答1:
You can create or modify a RippleDrawable
at run time using something like:
ColorStateList csl = ColorStateList.valueOf(Color.BLUE);
RippleDrawable d = new RippleDrawable(csl, null, null);
// Change the color, if desired.
ColorStateList otherCsl = ColorStateList.valueOf(Color.RED);
d.setColor(otherCsl);
回答2:
You can't use the default rippleview in android below api 21 You need to make a custom view with animation on touch. or you can easy use this one to add ripple to views: https://github.com/balysv/material-ripple
To add ripple from java :
MaterialRippleLayout.on(view)
.rippleColor(Color.BLACK)
.create();
来源:https://stackoverflow.com/questions/28817185/android-how-to-create-ripple-effect-in-java