Android how to create ripple effect in Java

走远了吗. 提交于 2019-12-24 02:09:51

问题


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

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