Search code examples
androidandroid-resources

how to add different colors to the Image resource randomly


I am having a circular image view

circleImageView.setImageResource(R.color.colorPrimary);

Instead of colorPrimary i want to add random colors

I have a array

arraystring = {R.color.colorPrimary,R.color.blue,R.color.red}

i used random function method to assign

String randomStr = arraystring [new Random().nextInt(array.length)];

but i cant give

circleImageView.setImageResource(randomStr);

Is their any other methods to give,can any one suggest it please


Solution

  • first declare the array as integer array

    int[] colors = new int[] {R.color.colorPrimary,R.color.blue,R.color.red};
    

    the choose from the integer array randomly

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

    finally set the color of the ImageView as follows

    circleImageView.setImageDrawable(new ColorDrawable(randomColor));
    

    Hope this helps..