How to set the background to a random color when a button is pressed on Android?

I am writing an application that changes the background color each time the button is pressed. And this is what I still have. But it does not work! What am I doing wrong?

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b = (Button) findViewById(R.id.button1); final View a = findViewById(R.id.m); final Random color = new Random(); final Paint p = new Paint(); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { p.setARGB(256,color.nextInt(256),color.nextInt(256),color.nextInt(256)); a.setBackgroundColor((p.getColor())); } }); } 

It works when I skip a single color, for example a.setBackgroundColor (Color.GREEN);

+4
source share
5 answers

I'm not sure if this will work (but worth a try):

Try initializing color = new Random () in the onClick () statement.

 b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { color = new Random(); p.setARGB(256,color.nextInt(256),color.nextInt(256),color.nextInt(256)); a.setBackgroundColor((p.getColor())); } }); 

Also look at this question:

Android: Create random color when clicked?

it looks like he is trying to achieve a similar goal.

+2
source

Maybe it's too late, but I was looking for the same thing, and reading this thread, I came up with a solution to the problem.

You use 256 for alpha, and also 256 for maximum random. but the values ​​to use are 0-255. if u change that it will work well.

 Random color = new Random(); a.setBackgroundColor(Color.argb(255, color.nextInt(255), color.nextInt(255), color.nextInt(255))); 

Greetings

+4
source

For random color, I wrote a method (you need to import android.graphics.Color; import java.util.Random;):

 int randomColor() { Random r = new Random(); int red = r.nextInt(256); int green = r.nextInt(256); int blue = r.nextInt(256); return Color.rgb(red, green, blue); } 

Then I just use it like this:

 Paint p = new Paint(); p.setColor(randomColor()); 
+2
source

You seem to be on the right track. Remember to get your seed, otherwise you will get the same "random" values ​​every time.

 Random color = new Random(System.currentTimeMillis()); 

Try wrapping it in a message.

 view.post(new Runnable() { @Override public void run() { // setbackground here } } 
0
source
 p.setARGB(200,color.nextInt(256),color.nextInt(256),color.nextInt(256)); a.setBackgroundColor((p.getColor())); 
-1
source

All Articles