Android: Generate random color on click?

Random rnd = new Random();
paint.setARGB(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));

or

Random rnd = new Random(); 
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));   
view.setBackgroundColor(color);

Though in your case it seems that you want to create a new drawable and assign it to your view. What is actually the drawable in your case? Is it an image, shape, fill...


to get random color values you can use this method:

public int getRandomColor(){
   Random rnd = new Random();
   return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}

then apply to your views:

myView.setBackgroundColor(getRandomColor());

enter image description here


So if you’re looking for a beautiful color palette, Maybe It's Not Such A Great Idea To use totally random values. This approach might not yield the best results, It always ends up with a selection of similar colors that way too dark or way too bright.

Semi-random approach :

If you need some fresh and shiny colors then use the following simple class, that I wrote previously when I had the same issues. It's semi-random and uses a predefined color palette:

class RandomColors {
    private Stack<Integer> recycle, colors;

    public RandomColors() {
        colors = new Stack<>();
        recycle =new Stack<>();
        recycle.addAll(Arrays.asList(
                0xfff44336,0xffe91e63,0xff9c27b0,0xff673ab7,
                0xff3f51b5,0xff2196f3,0xff03a9f4,0xff00bcd4,
                0xff009688,0xff4caf50,0xff8bc34a,0xffcddc39,
                0xffffeb3b,0xffffc107,0xffff9800,0xffff5722,
                0xff795548,0xff9e9e9e,0xff607d8b,0xff333333
                )
        );
    }

    public int getColor() {
        if (colors.size()==0) {
            while(!recycle.isEmpty())
                colors.push(recycle.pop());
            Collections.shuffle(colors);
        }
        Integer c= colors.pop();
        recycle.push(c);
        return c;
    }
}

Random Color Generator class for android


Random approach :

But if you're still considering use random approach you may want use this single line instead of multiple lines of code :

int color= ((int)(Math.random()*16777215)) | (0xFF << 24);

Random Color Generator android

The purpose of using this (0xFF << 24) is to set the alpha value to the maximum that means zero transparency.