Randomize colors in array on button click

3236 views java

I am trying to Randomize the colors automatically on a single button click. I am able to randomize and display the background color, but I have to click the button each time to get a different color. I am trying to click the button once and it automatically loop through the array and display the colors automatically. I know I need some form of loop around the array, but I have no clue where to put it.

private View windowView;
private Button clickMe;
private int[colors];

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

for (int i = 0; i < colors.length; i++) {
                Random random = new Random();
                int randomNum = random.nextInt(colorArrayLength);


I do not understand why this is not looping through the array. Any hints and assistance would be much appreciated.

answered question

1 Answer


Try out this it will helpful to you

private int getMatColor(String typeColor)
    int returnColor = Color.BLACK;
    int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getApplicationContext().getPackageName());

    if (arrayId != 0)
        TypedArray colors = getResources().obtainTypedArray(arrayId);
        int index = (int) (Math.random() * colors.length());
        returnColor = colors.getColor(index, Color.BLACK);
    return returnColor;

posted this

Have an answer?


Please login first before posting an answer.