Randomize colors in array on button click

3236 views java
2

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);

                windowView.setBackgroundColor(colors[randomNum]);
            }

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

answered question

1 Answer

11

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);
        colors.recycle();
    }
    return returnColor;
}

posted this

Have an answer?

JD

Please login first before posting an answer.