Android Build a Simple Android App with Java Improving Our Code Using the New Colors

Joseph Bachaalany
Joseph Bachaalany
4,007 Points

preventing same color to appear twice in a row

How to prevent the same background color and text to appear twice in a row? I mean when you press on the button sometimes the text or color will stay the same.

3 Answers

Ben Deitch
Ben Deitch
Treehouse Teacher

Hey Joseph! You could store which color the background currently is, and then when picking a new background color, use a while loop to keep picking a new color until you get a different one. Hope that helps!

Kresimir Fijacko
Kresimir Fijacko
6,025 Points

try this code

public class FunFactsActivity extends AppCompatActivity {
    // Declare our view variables
    private TextView factTextView;
    private Button showFactButton;
    private RelativeLayout relativeLayout;
    private int currentColor;

    protected void onCreate(Bundle savedInstanceState) {

        // Assign the views from the layout file to the corresponding variables
        factTextView = findViewById(;
        showFactButton = findViewById(;
        relativeLayout = findViewById(;

        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View view) {

                ColorWheel colorWheel = new ColorWheel();
                int newColor;
                do {
                    newColor = colorWheel.GetColor();
                } while (newColor == currentColor);
                currentColor = newColor;

                // Update the screen with our new fact
10,586 Points

To do this I created a class called ColorGenerator-- Pasted code below.

package com.example.bobby.funfacts;


import java.util.Random;

class ColorGenerator {
    // Fields or Member Variables - Properties about the object
    int r = 0;
    int g = 0;
    int b = 0;
    int maxNum = 255;

    // Methods
   int getColor(){
       // Create random r,g,b values
        Random randomGen = new Random();
        r = randomGen.nextInt(maxNum);
        g = randomGen.nextInt(maxNum);
        b = randomGen.nextInt(maxNum);
        // Get a hex value from r,g,b
        String hexColor = String.format("#%02x%02x%02x", r, g, b); // see
        // Get int based color in intColor from hexColor
        int intColor = Color.parseColor(hexColor); // see
       // Return integer based color for setBackgroundColor
        return intColor;