0

I have a problem changing the background color randomly:
First, I try to use parseColor In the Colorclass:

public class Colors {

       public String[] colors = {
            "#39add1", // light blue
            "#3079ab", // dark blue
            "#c25975" // mauve
       };

       public int getcolor() {
          Random randomGenerator = new Random();
          String color = "";

          int randomNumber = randomGenerator.nextInt(3);

          color = colors[randomNumber];
          int colorAsInt = Color.parseColor(color);
          return colorAsInt;
      }
} 

And in the Activity class:

View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
              int color = mColors.getcolor();
              relativeLayout.setBackgroundColor(color);
        }
};

It works perfectly:
But when I try to use String for return type of getcolor and use parse int in the activity class, when i run the app it gives me an error :Unfortunately app has stopped.

The color class:

public String getcolor() {
    Random randomGenerator = new Random();
    String color = "";

    int randomNumber = randomGenerator.nextInt(3);

    color = colors[randomNumber];
    return color;
}

And the activity class:

 View.OnClickListener listener = new View.OnClickListener() {
         @Override
         public void onClick(View view) {
               String color = mColors.getcolor();
               relativeLayout.setBackgroundColor(Integer.parseInt(color));
        }
 };

Why this problem happens?

JafarKhQ
  • 8,676
  • 3
  • 35
  • 45
habib
  • 91
  • 2
  • 6

2 Answers2

3

Integer.parseInt(color) cant parse the string because its not an integer string "#39add1".
You have to use Color.parseColor(color) like the first function.

relativeLayout.setBackgroundColor(Color.parseColor(color));
JafarKhQ
  • 8,676
  • 3
  • 35
  • 45
0

Change your colors definition to

public int[] colors = {
    0x39add1, // light blue
    0x3079ab, // dark blue
    0xc25975 // mauve
};

and use

setBackgroundColor(colors[0]);
Ridcully
  • 23,362
  • 7
  • 71
  • 86