Applying random background color to RecyclerView but not getting the same color twice in a row

by Bon Echo   Last Updated August 13, 2019 19:26 PM

I am trying to apply a random background color from a list of colors to RecyclerView list items, however, I am trying not to get the same color twice in a row I tried recursion with something like

fun setBackground(){
val newColor = getRandomColor()
if(newColor == lastColor){
setBackground()
}
/*..*\
}

where setBackground() is called in onBindViewHolder() and getRandomColor() returns a random color in an array from resources



Answers 2


Right now you're only setting the background if the newColor equals the lastColor. This is going to cause the background to always be the same color. You want do do

if(newColor != lastColor){
setBackground()
}
andrewgray0702
andrewgray0702
August 13, 2019 19:16 PM

You need to return the function after recursion call, or just place the rest of the code in else statement:

fun setBackground(){
val newColor = getRandomColor()
if(newColor == lastColor){
setBackground()
return;    //RETURN THE FUNCTION HERE
}

Alternative:

fun setBackground(){
val newColor = getRandomColor()
if(newColor == lastColor){
setBackground()
}else{
...
}

When your function comes back to the previous function, it sets the value again which overrides the color set earlier in stack.

Also, you can do this easily without recursion if the above code is confusing you:

val newColor;
do{  
newColor = getRandomColor()
}while(newColor == lastColor);
Zohaib Amir
Zohaib Amir
August 13, 2019 19:20 PM

Related Questions


Updated April 06, 2018 23:26 PM

Updated September 05, 2018 00:26 AM