Android adapter中设置文本颜色无效

在 adapter 中改变文本颜色无效

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.tvStatus.text = "文本"
    //无效
    holder.tvStatus.setTextColor(R.color.colorAccent)
}

其中一种有效的办法

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.tvStatus.text = "文本"
    //有效
    holder.tvStatus.setTextColor(color.parseColor("#43c013"))
}

但是这样就只能写死在代码里面,要改比较麻烦。另一种解决办法,在 Adapter 构造函数中传入当前页面,使得能够使用 getResources()

class MyAdapter(viewModel: MyViewModel,context: Context) :
    RecyclerView.Adapter<MyAdapter.ViewHolder>() {
    val color=context.resources.getString(R.color.colorAccent)

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): AttendanceAdapter.ViewHolder {
        return LayoutInflater.from(parent.context)
            .inflate(R.layout.cell_attendance, parent, false)
    }

    override fun getItemCount(): Int {...}

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.tvStatus.text = "文本"
        holder.tvStatus.setTextColor(color.parseColor(color))
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvStatus: TextView

        init {
            tvStatus = view.findViewById(R.id.tvStatus)
        }
    }
}
posted @ 2021-01-31 22:19  欧辰陆  阅读(388)  评论(0编辑  收藏  举报