android - How to change item background color in recyclerview, getting value from Shared Preferencess
问题描述
I am new android developer. I have activity with radio buttons and I can choose color,put it into sharedPreferences and set background color to item in recycleview. Here is it my code:
class ListAdapter(private val context: RecyclerView, private val ideasList: ArrayList<DataItem>) :
RecyclerView.Adapter<ListAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title: TextView = itemView.title_idea
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_list, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return ideasList.count()
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val idea: DataItem = ideasList[position]
holder.title.text = idea.title
}
}
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
val sharedPreferences = getSharedPreferences(CHANGE_COLOR_SETTING, Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
radio_group.setOnCheckedChangeListener { _, id ->
when (id) {
R.id.set_green_color_item -> editor.putBoolean(CHANGE_TO_GREEN_COLOR, true)
R.id.set_pink_color_item -> editor.putBoolean(CHANGE_TO_PINK_COLOR, true)
R.id.set_blue_color_item -> editor.putBoolean(CHANGE_TO_BLUE_COLOR, true)
}
editor.apply()
}
}
companion object {
private const val CHANGE_COLOR_SETTING = "change_color_setting"
private const val CHANGE_TO_GREEN_COLOR = "change_to_green_color"
private const val CHANGE_TO_PINK_COLOR = "change_to_pink_color"
private const val CHANGE_TO_BLUE_COLOR = "change_to_blue_color"
}
}
Thank you for answers!
解决方案
I don't understand your question. Do you mean the color of each item inside the RecyclerView or the background color of the RecyclerView?
For each item you would have to do it inside your adapter with some logic. An option would be changing your model data(your ideaList), and call notifyDataSetChanged() to your adapter. Then inside your adapter you would have the logic to change the background color of each view.
If you want to change the background color of your whole RecyclerView then RecyclerView is like any other View and you can use code like this:
yourRecyclerView.setBackgroundColor(Color.BLUE)
推荐阅读
- amazon-web-services - 如何连接到远程 hashcorp Vault 服务器
- awk - 提取与特定模式匹配的行 + 额外操作
- python - 带有只能出现在一个销售活动中的外键列表的 Django 销售活动模型?
- alasql - REGEXP 字边界未按预期工作
- wordpress - 子文件夹正在重定向到根目录,它不应该
- excel - 禁用保存/另存为excel的按钮,但使用按钮保存
- javascript - PHP 未接收到图像请求发送的完整 GET 参数
- python - 如何计算具有最小权重的单射/满射图?
- javascript - 在中性节点服务器中接收 http 请求
- vue.js - preventDefault 不适用于车轮事件 [已解决]