Jared
Jared

Reputation: 4983

Android: Generate random color on click?

I have an ImageView, in which I am programmaticly creating drawables and presenting them to the user. My goal is to click on said ImageView and change the drawable's color.

How would I go about the random color changing bit? I am currently tinkering with Random(), Color.argb() and a few other things, but I can't seem to get it to work!

Upvotes: 117

Views: 138464

Answers (17)

ucMax
ucMax

Reputation: 5458

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 (Java):

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 (Java):

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.

semi-random (Kotlin)

class RandomColors() {
    private val recycle:Stack<Int> = Stack()
    private val colors:Stack<Int> = Stack()
    init {
        recycle.addAll(
            Arrays.asList(
                // ARGB hex to int >> (0xFFEE5670.toInt(),...)
                -0xbbcca, -0x16e19d, -0x63d850, -0x98c549,  
                -0xc0ae4b, -0xde690d, -0xfc560c, -0xff432c,
                -0xff6978, -0xb350b0, -0x743cb6, -0x3223c7,
                -0x14c5, -0x3ef9, -0x6800, -0xa8de,
                -0x86aab8, -0x616162, -0x9f8275, -0xcccccd
            )
        )
    }

    fun getColor(): Int {
        if (colors.size == 0)
            while (!recycle.isEmpty()) colors.push(recycle.pop())
            Collections.shuffle(colors)
        val c = colors.pop()
        recycle.push(c)
        return c
    }
}

Random approach (Kotlin):

val color = (Math.random() * 16777215).toInt() or (0xFF shl 24)

Random approach (Compose):

fun randomColor(alpha:Int=255) = Color(
    Random.nextInt(256),
    Random.nextInt(256),
    Random.nextInt(256),
    alpha = alpha)

preferentially :

val randomColor
    get() = Color(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))

Upvotes: 28

Zakhar Rodionov
Zakhar Rodionov

Reputation: 1493

Random color in Jetpack Compose

val RandomColor
    get() = Color(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))

Upvotes: 2

Amir J
Amir J

Reputation: 123

Here is an extension to do the same:

fun Int.Companion.randomColor(): Int
{
    return Color.argb(255,
                      Random.nextInt(256),
                      Random.nextInt(256),
                      Random.nextInt(256))
}

and this is the usage:

myTextView.setBackgroundColor(Int.randomColor());

Upvotes: 3

abhi
abhi

Reputation: 1136

Simplest Sol... Change the range to avoid dark or light color.. like 30 to 200 to avoid black and white family..

val randomColor: Int
    get() {
        return Color.rgb((30..200).random(),(30..200).random(),(30..200).random())
    }

Upvotes: 2

Sagar H
Sagar H

Reputation: 5541

I hope the following two solutions may help you.

There are two way to get random colors programmatically to set to view

1.First solution

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

If you are using in adapter on scroll you may get random colors for the same view this may not look good, to avoid this you can use the second solution.

2.Second Solution

You can use ColorGenerator.DEFAULT instead of ColorGenerator.MATERIAL as per your choice. You can also use any number instead of position

 ColorGenerator generator = ColorGenerator.MATERIAL; 
    int color = generator.getColor(position);
    holder.mEvent_color_strip.setBackgroundColor(color);

Upvotes: 1

King of Masses
King of Masses

Reputation: 18765

You can use ColorGenerator for picking the random color

ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT

int color1 = generator.getRandomColor();      // generate random color

If you want to have the same specific color code for repeated same usernames. you can use like below

public int getColorCode(String userName)
    {
        ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
        // generate color based on a key (same key returns the same color), useful for list/grid views
        int colorCode = generator.getColor(userName);

        return colorCode;
    }

Upvotes: 3

paul_f
paul_f

Reputation: 1375

In Kotlin:

val rnd = Random()
val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
myView.setBackgroundColor(color)

Upvotes: 8

Kamran
Kamran

Reputation: 19

public static String rndColor()
    {
        Random random = new Random();
        int num = random.nextInt(16777215);
        String hex = "";
        while (num != 0)
        {
            if (num % 16 < 10)
                hex = Integer.toString(num % 16) + hex;
            else
                hex = (char)((num % 16)+55) + hex;
            num = num / 16;
        }

        return "#"+((hex.length()<6)?String.format("%0"+(6-hex.length())+"d", 0):"") + hex;
    }

Upvotes: 0

Miramax Mars
Miramax Mars

Reputation: 146

In your case you should do like here, it's work to me

@Override
public void onBindViewHolder(@NonNull WeatherMainAdapter.ViewHolder holder, int position) {
    Random rnd = new Random();
    int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    holder.date.setText(items.get(position).getDt_txt());
    holder.temp.setText(items.get(position).main.getTemp());
    holder.press.setText(items.get(position).main.getPressure());
    holder.cardView.setBackgroundColor(color);
}

Upvotes: 0

Sohaib Aslam
Sohaib Aslam

Reputation: 1315

Most Accurate Solution of this problem:

-First, add this in the gradle (app),

compile 'com.github.lzyzsd.randomcolor:library:1.0.0'

then compile and rebuild the app.

-The second step just use it by this way,

RandomColor randomColor = new RandomColor();

Button l = findviewbyid(R.id.B1);
l.setBackgroundColor(randomColor.randomColor());

Reference Link:

https://github.com/lzyzsd/AndroidRandomColor

Upvotes: 0

Gary Davies
Gary Davies

Reputation: 960

thing.setBackgroundColor(new Random().nextInt());

Upvotes: 5

Jorgesys
Jorgesys

Reputation: 126465

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

Upvotes: 20

Mukesh Patil
Mukesh Patil

Reputation: 11

bb.setBackgroundColor(Color.rgb(
    getRandomInteger(0,255),
    getRandomInteger(0, 255),
    getRandomInteger(0, 255)
));

Upvotes: 0

Raghav Thakkar
Raghav Thakkar

Reputation: 311

 public static int randomColor(){
    float[] TEMP_HSL = new float[]{0, 0, 0};
    float[] hsl = TEMP_HSL;
    hsl[0] = (float) (Math.random() * 360);
    hsl[1] = (float) (40 + (Math.random() * 60));
    hsl[2] = (float) (40 + (Math.random() * 60));
    return ColorUtils.HSLToColor(hsl);
}

Upvotes: 1

Sumit
Sumit

Reputation: 1122

This is my code I used in an application, it may help you.

It generates a random color on touch

 public boolean onTouch(View v, MotionEvent event) {
            int x = (int)event.getX();
            int y = (int) event.getY();
            float w = v.getWidth();

            if(x < (w * (1.0/3) )){
                layout.setBackgroundColor(Color.rgb(255,x,y));
            }else if(x < (w * (2.0 / 3))){
                layout.setBackgroundColor(Color.rgb(x,255,y));
            }else{
                layout.setBackgroundColor(Color.rgb(x,y,255));
            }
            return true;
   }

Upvotes: 1

Kevin
Kevin

Reputation: 837

I met this and this is my code,May some help

 /**
 * view-source:http://www.kareno.org/js/colors/ 参考
 *Get Random background color and the text color for the background
 * @return 0--》background
 *          1--》text color
 */
public static  int[] getRandomColor() {
    Random random = new Random();
    int RGB = 0xff + 1;
    int[] colors = new int[2];
    int a = 256;
    int r1 = (int) Math.floor(Math.random() * RGB);
    int r2 = (int) Math.floor(Math.random() * RGB);
    int r3 = (int) Math.floor(Math.random() * RGB);
    colors[0] = Color.rgb(r1, r2, r3);
    if((r1 + r2 + r3) > 450) {
        colors[1] = Color.parseColor("#222222");
    }else{
        colors[1] = Color.parseColor("#ffffff");
    }
    return colors;
}

Upvotes: 5

Lumis
Lumis

Reputation: 21639

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...

Upvotes: 374

Related Questions