Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import android.content.res.ColorStateList;

import android.graphics.Color;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.StateSet;

import java.util.Arrays;

public class Main {
    @NonNull
    public static Drawable getAdaptiveRippleDrawable(int normalColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new RippleDrawable(ColorStateList.valueOf(darker(normalColor)), getRippleMask(normalColor),
                    null);
        } else {
            return getStateListDrawable(normalColor, darker(normalColor));
        }
    }

    public static int darker(int color) {
        int r = Color.red(color);
        int b = Color.blue(color);
        int g = Color.green(color);

        return Color.rgb((int) (r * .9), (int) (g * .9), (int) (b * .9));
    }

    @NonNull
    private static Drawable getRippleMask(int color) {
        float[] outerRadii = new float[8];
        // 3 is radius of final ripple,
        // instead of 3 you can give required final radius
        Arrays.fill(outerRadii, 3);

        RoundRectShape r = new RoundRectShape(outerRadii, null, null);
        ShapeDrawable shapeDrawable = new ShapeDrawable(r);
        shapeDrawable.getPaint().setColor(color);

        return shapeDrawable;
    }

    @NonNull
    private static StateListDrawable getStateListDrawable(int normalColor, int pressedColor) {
        StateListDrawable states = new StateListDrawable();
        states.addState(new int[] { android.R.attr.state_pressed }, new ColorDrawable(pressedColor));
        states.addState(new int[] { android.R.attr.state_focused }, new ColorDrawable(pressedColor));
        states.addState(new int[] { android.R.attr.state_activated }, new ColorDrawable(pressedColor));
        states.addState(new int[] {}, new ColorDrawable(normalColor));
        states.addState(StateSet.WILD_CARD, new ColorDrawable(normalColor));
        return states;
    }
}