Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Help with Extra Credit!

"Extra Credit Change the background color when the button is tapped

Add an ID to the RelativeLayout element in activity_main.xml. Then you can use that ID to get a RelativeLayout object just like we get a TextView and Button. The RelativeLayout object has a method called setBackgroundColor() that takes an int color code as a parameter. Use a color code from the Color class, i.e. Color.GREEN, and call this method when the button is clicked."

Okay so I was able to work this out, but now I want to challenge myself and take it to the next level. How do I make this same program, but randomizing the color? Meaning, not always change it to green?

Thanks!

1 Answer

Gergő Bogdán
Gergő Bogdán
6,664 Points

One option would be to create an Array of Colors, where you'd add a couple of colors by default (5-6). The you would use the Random class from Java. This has a nextInt() method and can have a parameter which specifies the max value of the generated random number, for example:

Color[] colors= new Color[] { Color.GREEN, Color.RED};

Random rnd = new Random();
int randomNumber = rnd.nextInt(colors.length);
Color randomColor = colors[randomNumber];

How do I call the array using the ".setBackgroundColor(?)"? And why do you initiate with "Color []" ? Can it be "int [] colors" instead?

Thank you