You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Kotlin随机背景色生成异常求助

问题分析与解决

你的问题出在两处关键错误:

1. 错误的数组尺寸计算

你写的arrayOf(R.array.allColors)是创建了一个只包含单个元素的数组(这个元素就是颜色数组的资源ID R.array.allColors),所以它的size永远是1。(0 until 1).random()的结果永远是0,导致所有item都用同一个“元素”——也就是那个资源ID本身,这完全不是你要的颜色数组。

2. 直接传递资源ID作为颜色值

就算你拿到了正确的索引,直接把R.array.allColors里的字符串颜色值或者资源ID传给setCardBackgroundColor也是错误的,需要把字符串格式的颜色值解析成Int类型的颜色值。


修正后的完整代码

第一步:修改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,
    private val colorList: List<Int> // 传入解析好的颜色列表
) : 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 randomColor = colorList.random()
        holder.bind(allLocationslist[position], randomColor)
        
        holder.itemView.setOnClickListener { 
            onClickCallback.invoke(allLocationslist[position])
        }
    }

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

第二步:在Activity/Fragment中初始化颜色列表并传入Adapter

在你创建Adapter的地方,先从资源中加载颜色数组并解析:

// 从资源中获取字符串颜色数组
val colorStrings = resources.getStringArray(R.array.allColors)
// 解析成Int类型的颜色列表
val colorList = colorStrings.map { Color.parseColor(it) }

// 创建Adapter时传入颜色列表
val adapter = CustomAdapter(allLocationslist, { item -> /* 你的点击逻辑 */ }, colorList)

额外优化:固定城市对应颜色(可选)

如果希望同一个城市每次显示的颜色固定(避免RecyclerView滚动时颜色变化),可以用城市名称的哈希值来计算索引,而不是随机:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val cityItem = allLocationslist[position]
    // 用城市名的哈希值取模,得到固定索引
    val colorIndex = cityItem.city.hashCode() % colorList.size
    val fixedColor = colorList[Math.abs(colorIndex)] // 取绝对值避免负数
    holder.bind(cityItem, fixedColor)
    
    holder.itemView.setOnClickListener { 
        onClickCallback.invoke(cityItem)
    }
}

内容的提问来源于stack exchange,提问作者Shreyas Shetty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:15:50