Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

android - Kotlin : How to update a value of a RecyclerView

I want to update at any time some values in my RecyclerView.

Here is my data class ParameterText:

data class ParameterText(
    var parameterName: String?,
    var parameterValue: String?
)

Here is my ViewHolder class ParameterTextViewHolder:

class ParameterTextViewHolder(itemView: View) : ViewHolder(itemView) {
    val parameterName: TextView = itemView.findViewById(R.id.parameterName)
    val parameterText: TextView = itemView.findViewById(R.id.parameterValue)
}

Here is my Adapter (in my Activity):

// Adapter
private val parametersTextFoundList = emptyDataSourceTyped<ParameterText>()

And here is my RecyclerView setup (also in my Activity):

rv_parameters_text.setup {
    withDataSource(parametersTextFoundList)
    withItem<ParameterText, ParameterTextViewHolder>(R.layout.parameter_text) {
        onBind(::ParameterTextViewHolder) { _, item ->
            parameterName.text = item.parameterName
            parameterText.text = item.parameterValue
        }
    }
}

I tried this:

private fun updateValue(index: Int, value: String) {
    parametersTextFoundList[index].parameterValue = value
}

But it doesn't work. I read that I should also use the notifyDataSetChanged() method but I don't know where to use it. Can you help me?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is an entire suite of notify API's, including notifyItemInserted(), notifyItemRemoved(), notifyItemChanged(), which are designed to more efficiently update a RecyclerView.

when changing the contents of one existing row in your RecyclerView, its more efficient to use adapter.notifyItemChanged(row), as notifyDataSetChanged() will reload the entire RecyclerView. I recommend:

private fun updateValue(index: Int, value: String) 
{
    parametersTextFoundList[index].parameterValue = value
    rv_parameters_text.adapter?.notifyItemChanged(index)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...