Android: Generate random color on click?

一个人想着一个人 提交于 2019-11-26 06:19:03

问题


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!


回答1:


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




回答2:


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




回答3:


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


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




回答4:


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



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



回答6:


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



回答7:


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



回答8:


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



回答9:


Hope the following two solution may help you.

There are two way to get random colors programatically 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 same view this may not look good, to avoid this you can use 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);



回答10:


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



回答11:


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




回答12:


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



回答13:


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



回答14:


In Kotlin:

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


来源:https://stackoverflow.com/questions/5280367/android-generate-random-color-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!