1
LinearLayout abc = findViewById(R.id.view);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener((new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int max = 1;
                int min = 225;
                Random rand = new Random();
                int a = rand.nextInt((max - min) + 1) + min;
                int b = rand.nextInt((max - min) + 1) + min;
                int c = rand.nextInt((max - min) + 1) + min;
                int d = rand.nextInt((max - min) + 1) + min;
                abc.setBackgroundColor(Color.argb(a, b, c, d));
            }

        }));

I tried with Switch too but my app is closed or return to previous Activity.

2 Answers2

0
LinearLayout abc = findViewById(R.id.view);
        //abc.setBackgroundColor(Color.argb(255, 56, 170, 255));
        Button button = (Button) findViewById(R.id.button);
button.setOnClickListener((new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int a = ThreadLocalRandom.current().nextInt(1, 255);
                int b = ThreadLocalRandom.current().nextInt(1, 255);
                int c = ThreadLocalRandom.current().nextInt(1, 255);
                int d = ThreadLocalRandom.current().nextInt(1, 255);
                abc.setBackgroundColor(Color.argb(a,b,c,d));

            }

        }));

You were also so much help full Anil Thankyou for answering. Here is my twitter account I just started yesterday uploading Maybe it will be helpful in future.

-1

Change Background Color of a Layout

If your requirement is changing Background color of a layout Dynamically means, Try any of the below

If you are outside an activity

abc.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

If you are on activity

abc.setBackgroundColor(getResources().getColor(R.color.red));

If you want to set color from Android Graphics color

abc.setBackgroundColor(Color.RED);

If you want to set color from using Hexa Code

abc.setBackgroundColor(Color.parseColor("#FFFFFF"));

OR If you want to set color randomly

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

and this is the usage:abc.setBackgroundColor(Int.randomColor());

G Anil Reddy
  • 19
  • 1
  • 6