Android: Generate random color on click?

AndroidColorsImageview

Android Problem Overview


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!

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

Solution 3 - Android

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.

Solution 4 - Android

In Kotlin:

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

Solution 5 - Android

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;
}

Solution 6 - Android

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

Solution 7 - Android

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;
    }

Solution 8 - Android

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())
    }

Solution 9 - Android

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());

Solution 10 - Android

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;
   }

Solution 11 - Android

 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);
}

Solution 12 - Android

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);

Solution 13 - Android

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

Solution 14 - Android

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

Solution 15 - Android

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);
}

Solution 16 - Android

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;
    }

Solution 17 - Android

Random color in Jetpack Compose

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJaredView Question on Stackoverflow
Solution 1 - AndroidLumisView Answer on Stackoverflow
Solution 2 - AndroidJorgesysView Answer on Stackoverflow
Solution 3 - AndroiducMediaView Answer on Stackoverflow
Solution 4 - Androidpaul_fView Answer on Stackoverflow
Solution 5 - AndroidKevinView Answer on Stackoverflow
Solution 6 - AndroidGary DaviesView Answer on Stackoverflow
Solution 7 - AndroidKing of MassesView Answer on Stackoverflow
Solution 8 - AndroidabhiView Answer on Stackoverflow
Solution 9 - AndroidAmir JView Answer on Stackoverflow
Solution 10 - AndroidSumitView Answer on Stackoverflow
Solution 11 - AndroidRaghav ThakkarView Answer on Stackoverflow
Solution 12 - AndroidSagarView Answer on Stackoverflow
Solution 13 - AndroidMukesh PatilView Answer on Stackoverflow
Solution 14 - AndroidSohaib AslamView Answer on Stackoverflow
Solution 15 - AndroidМаксим СыроваткаView Answer on Stackoverflow
Solution 16 - AndroidKamranView Answer on Stackoverflow
Solution 17 - AndroidZakhar RodionovView Answer on Stackoverflow