115

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!

Konstantin Burov
  • 68,980
  • 16
  • 115
  • 93
Jared
  • 4,823
  • 6
  • 23
  • 15

17 Answers17

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

Lumis
  • 21,517
  • 8
  • 63
  • 67
  • 16
    Shouldn't it be 256 instead of 255 everywhere? The API for nextInt() says "Returns a pseudo-random uniformly distributed int in the half-open range [0, n)" – Catalin Morosan Oct 28 '11 at 13:09
  • 1
    Kaciula, you are right the n is excluded: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html – Lumis Dec 31 '11 at 10:20
  • int color = 0xFF000000 | rnd.nextInt(0xFFFFFF); " use only 1 random instead of 3" – Umesh Chhabra Jun 01 '16 at 16:43
  • Color.argb function requires API at least 26 to work. – That's Enam Mar 27 '18 at 17:42
  • 2
    @That'sEnam nope, there are two Color.argb functions, one takes int arguments and has existed since API level 1, the one you are talking about takes float arguments and yes, is only since API 26 – Shane Monks O'Byrne Jun 02 '18 at 09:47
21

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)
ucMedia
  • 4,105
  • 4
  • 38
  • 46
20

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

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
8

In Kotlin:

val rnd = Random()
val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
myView.setBackgroundColor(color)
paul_f
  • 1,296
  • 17
  • 20
5

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;
}
Kevin
  • 781
  • 1
  • 9
  • 18
5
thing.setBackgroundColor(new Random().nextInt());
Gary Davies
  • 920
  • 15
  • 12
3

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;
    }
King of Masses
  • 18,405
  • 4
  • 60
  • 77
3

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());
Amir J
  • 123
  • 8
2

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())
    }
abhi
  • 961
  • 9
  • 13
1

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;
   }
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Sumit
  • 1,022
  • 13
  • 19
  • What exactly does this do? It looks like it's meant to factor in the position of the touch – Kartik Chugh Dec 07 '17 at 07:54
  • it will change the background of view on touch, when you touch and move, it will generate random color according to x y position and apply to view – Sumit Dec 07 '17 at 16:04
1
 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);
}
Raghav Thakkar
  • 311
  • 5
  • 12
1

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);
Sagar
  • 5,273
  • 4
  • 37
  • 50
1

Random color in Jetpack Compose

val RandomColor
    get() = Color(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))
Zakhar Rodionov
  • 1,398
  • 16
  • 18
0
bb.setBackgroundColor(Color.rgb(
    getRandomInteger(0,255),
    getRandomInteger(0, 255),
    getRandomInteger(0, 255)
));
NaviRamyle
  • 3,967
  • 1
  • 31
  • 49
0

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

Sohaib Aslam
  • 1,245
  • 17
  • 27
0

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);
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
Miramax Mars
  • 147
  • 2
  • 3
0
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;
    }
Kamran
  • 19
  • 3