0

I'm trying to start up an application I'm working on with a random background color each time. I've seen a few threads about this on here but nothing has seemed to help me out.

In activity_main.xml it has "android:background="#F799B3" and this is the part where I would like a random color generated each time...any suggestions?

Many thanks.

  • 1
    did you try [this]?(http://stackoverflow.com/questions/5280367/android-generate-random-color-on-click) You should get a reference to the activity's parent view in order to set it programatically – mmark Mar 20 '15 at 17:34

3 Answers3

3

In your MainActivity.java put this in onCreate

    Random rnd = new Random();
    int color = Color.argb(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    findViewById(android.R.id.content).setBackgroundColor(color);

If you always want full colors replace the first argument of argb with 255

AKroell
  • 622
  • 4
  • 18
1

Ok you can do this. Set your layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/myLayout" >



</LinearLayout>

Then you on the .java get a random number with

Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();

And finally add in the method onCreate:

View layoutView = findViewById(R.id.myLayout;
layoutView.setBackgroundColor(Color.rgb(Math.round(r), 
                                        Math.round(g), 
                                        Math.round(b) ) );
0
  1. Modify your activity main xml and every possible xmls which can set the background color.

    You have to remove the line "android:background="#F799B3"" from main layout. Don't set the background in xml at all.

  2. Then, in your MainActivity.java try setting it after you inflat the layout. Just like shown here: https://stackoverflow.com/users/3767038/awk

Now, if you set it in onCreate(), it will change every time you open up your main activity. If you want to have random color background just once, on startup only, the you have to work with SavedInstances in your application.

Example:

In your onCreate():

 int lastUsedColor = 0 ;
 if(savedInstanceState != null){
   lastUsedColor = savedInstanceState.getInt("lastUsedColor");
   findViewById(android.R.id.content).setBackgroundColor(lastUsedColor);
 }else{
   Random rnd = new 
   int newColor = Color.argb(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
   findViewById(android.R.id.content).setBackgroundColor(newColor);
   savedInstanceState.putInt("lastUsedColor", newColor);
   lastUsedColor = newColor;
 }

In your onSaveInstanceState(Bundle bundle)

super.onSaveInstanceState(bundle);
bundle.putInt("lastUsedColor", lastUsedColor);

Hope it helps.

Community
  • 1
  • 1
dhun
  • 643
  • 7
  • 13