Home > Software design >  Android Studio: Kotlin Random Number Generator not working
Android Studio: Kotlin Random Number Generator not working

Time:07-24

I am using CardView in RecyclerView for displaying a list of City names.

Along with the city name, I would like to add a curved square image containing a random background colour and the starting letter of the city name, just like the default image of our Gmail accounts.

I have tried the following approach for generating a random index in the colours array and passing the colour to the ViewHolder class of my CustomAdapter.

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <string-array name="allColors">
        <item>#99cc00</item>
        <item>#33b5e5</item>
        <item>#0099cc</item>
        <item>#547bca</item>
        <item>#aa66cc</item>
        <item>#9933cc</item>
        <item>#669900</item>
        <item>#aeb857</item>
        <item>#cc0000</item>
        <item>#df5948</item>
        <item>#ff4444</item>
        <item>#ae6b23</item>
        <item>#ff8800</item>
        <item>#e5ae4f</item>
        <item>#ffbb33</item>
        <item>#cccccc</item>
        <item>#888888</item>
    </string-array>

</resources>

CustomAdapter.kt

package com.x.y.z
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.x.y.z.databinding.CityCardviewActivityBinding
import com.x.y.z.models.LocationWeather
import com.x.y.z.models.LocationWeatherItem
import kotlin.random.Random


class CustomAdapter(private val allLocationslist : LocationWeather, private val onClickCallback :  (LocationWeatherItem) -> Unit) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    class ViewHolder(private val binding: CityCardviewActivityBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bind(get: LocationWeatherItem, color: Int) {
            binding.city.text = get.city
            binding.firstLetter.text = get.city[0].toString()
            binding.roundCardView.setCardBackgroundColor(color)
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = CityCardviewActivityBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val idx = (0 until arrayOf(R.array.allColors).size).random()
        holder.bind(allLocationslist[position], arrayOf(R.array.allColors)[idx])
        holder.itemView.setOnClickListener { v ->
            onClickCallback.invoke(allLocationslist[position])
        }

    }

    override fun getItemCount(): Int {
        return allLocationslist.size
    }
}

I just generated a random index using the below method and passed the value at that index to the ViewHolder Class.

val idx = (0 until arrayOf(R.array.allColors).size).random()

But the background colour for all the CardViews is the same when run.

enter image description here

I have just started my journey in Android and am not able to figure out the mistake. I kindly request our community members to share their valuable insights. Thank you.

CodePudding user response:

arrayOf(R.array.allColors) gives you a list containing only one item which is the id for allColors. You can use this to get the list of the colors

val randomColor = resources.getStringArray(R.array.exo_playback_speeds).random()

CodePudding user response:

R class contains resource identifiers that are just ints. So, arrayOf(R.array.allColors) is an array of just one integer which is a resource id and not any of your color values.

To access array resources, replace arrayOf(R.array.allColors) with something like resources.getIntArray(R.array.allColors).

CodePudding user response:

First of all in color.xml define your colors and create array of it.

<?xml version="1.0" encoding="utf-8"?>
<resources>

<item name="blue" type="color">#FF33B5E5</item>
<item name="purple" type="color">#FFAA66CC</item>
<item name="green" type="color">#FF99CC00</item>
<item name="orange" type="color">#FFFFBB33</item>
<item name="red" type="color">#FFFF4444</item>
<item name="darkblue" type="color">#FF0099CC</item>
<item name="darkpurple" type="color">#FF9933CC</item>
<item name="darkgreen" type="color">#FF669900</item>
<item name="darkorange" type="color">#FFFF8800</item>
<item name="darkred" type="color">#FFCC0000</item>

<integer-array name="androidcolors">
    <item>@color/blue</item>
    <item>@color/purple</item>
    <item>@color/green</item>
    <item>@color/orange</item>
    <item>@color/red</item>
    <item>@color/darkblue</item>
    <item>@color/darkpurple</item>
    <item>@color/darkgreen</item>
    <item>@color/darkorange</item>
    <item>@color/darkred</item>
</integer-array>

</resources>

Now generate random color like below in onCreate method.

int[] androidColors = getResources().getIntArray(R.array.androidcolors);
int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];

Lastly set this generated color.

view.setBackgroundColor(randomAndroidColor); 

Source taken from here.

  • Related