Подтвердить что ты не робот

Android: Генерировать случайный цвет при нажатии?

У меня есть ImageView, в котором я программно создаю чертежи и представляю их пользователю. Моя цель - щелкнуть по указанному ImageView и изменить выделяемый цвет.

Как мне пойти на случайный бит изменения цвета? В настоящее время я занимаюсь Random(), Color.argb() и несколькими другими вещами, но я не могу заставить его работать!

4b9b3361

Ответ 1

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

или

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

Хотя в вашем случае кажется, что вы хотите создать новый drawable и назначить его вашему представлению. Что на самом деле можно сделать в вашем случае? Это изображение, форма, заполнение...

Ответ 2

чтобы получить случайные значения цвета, вы можете использовать этот метод:

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

затем примените к вашим представлениям:

myView.setBackgroundColor(getRandomColor());

введите описание изображения здесь

Ответ 3

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

Ответ 4

Я встретил это, и это мой код, помогите

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

Ответ 5

Это мой код, который я использовал в приложении, он может вам помочь.

Он генерирует случайный цвет при касании

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

Ответ 6

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

Ответ 7

Надеюсь, что следующие два решения могут помочь вам.

Есть два способа получить случайные цвета программно, чтобы установить для view

1. Первое решение

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

Если вы используете adapter при прокрутке, вы можете получить случайные цвета для одного и того же view это может выглядеть не очень хорошо, чтобы избежать этого, вы можете использовать второе решение.

2. Второе решение

Вы можете использовать ColorGenerator.DEFAULT вместо ColorGenerator.MATERIAL по вашему выбору. Вы также можете использовать любое number вместо position

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

Ответ 8

Наиболее точное решение этой проблемы:

-First, добавьте это в Gradle (приложение),

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

затем скомпилируйте и пересоберите приложение.

-The второй шаг, просто используйте его таким образом,

RandomColor randomColor = new RandomColor();

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

Ссылка Ссылка:

https://github.com/lzyzsd/AndroidRandomColor

Ответ 9

Создать случайный цвет материала

 view.setBackgroundColor(getRandomMaterialColor("400"));

 private int getRandomMaterialColor(String typeColor) {   
            int returnColor = Color.GRAY;
            int arrayId = context.getResources().getIdentifier("mdcolor_" + typeColor, "array", context.getPackageName());

            if (arrayId != 0) {
                TypedArray colors = context.getResources().obtainTypedArray(arrayId);
                int index = (int) (Math.random() * colors.length());
                returnColor = colors.getColor(index, Color.GRAY);
                colors.recycle();
            }
            return returnColor;
        }

Ответ 10

В вашем случае вы должны сделать, как здесь, это работает для меня

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

Ответ 11

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

Ответ 12

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