How to set background to a random color at button press in Android?
android, background-color
Solution
I'm not sure if this will work (but it's worth a try):
Try initializing color = new Random() within 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: Generate random color on click?
it seems like it's trying to accomplish a similar goal.
Problem
I'm writing an app which changes the background color of the activity each time you press the button. And this is what I have till now. But it is not working! 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's working when I pass a single color, for example a.setBackgroundColor(Color.GREEN);