首页 > 解决方案 > 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!

标签: androidkotlin

解决方案


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)

推荐阅读