create Random Background Selector - Android java.util

Android examples for java.util:Random

Description

create Random Background Selector

Demo Code


import java.util.Random;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;

public class Main{
    // w ww  .  j a  v  a2  s . co m
    public static Drawable createRandomBackgroundSelector() {
        StateListDrawable stateListDrawable = new StateListDrawable();

        int[] pressedStateSet = new int[] { android.R.attr.state_enabled,
                android.R.attr.state_pressed };

        int[] normalStateSet = new int[] {};
        stateListDrawable.addState(pressedStateSet,
                createRandomColorBackground());
        stateListDrawable.addState(normalStateSet,
                createRandomColorBackground());
        return stateListDrawable;
    }
    
    public static Drawable createRandomColorBackground() {
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setCornerRadius(5);
        gradientDrawable.setShape(GradientDrawable.RECTANGLE);
        gradientDrawable.setColor(UIUtil.createRandomColor());
        return gradientDrawable;
    }
    
    public static int createRandomColor() {
        Random random = new Random();

        int red = random.nextInt(200); 
        int green = random.nextInt(200); 
        int blue = random.nextInt(200); 
        return Color.rgb(red, green, blue);
    }
}

Related Tutorials