Update Recycler View Child with any action on another child

DisplayName :

I am struggling with one feature that I need to implement in recycler view, I need to update few child based on the action performed on any child.

E.g. I have recycler view with lets say 10 items

  1. Child 1
  2. Child 2
  3. Child 3
  4. -
  5. -
  6. Child 10

Now at a time there are only 5 child that are visible on the screen and rest of them comes only when the list is scrolled. What I wanted to achieve is when I click on child 1 and perform an action, that action returns me to update random Child 4, Child 7 & Child 8

Now the problem is how do I update the child which isn't visible in the list.

I have tried using following solution:-

val childCount = rvQuestion.childCount
for (i in 0 until childCount) {
    val child = rvQuestion.getChildAt(i)
            .findViewById<TextInputEditText>(R.id.etQuestion)
    val questionHint = child.hint
    // list is the list of child that needs to be populated with a hint
    if(list.contains(questionHint)) {
        child.setText("someValue")
    }
}

The issue is recycler view never gives the childCount as 10 it gives only 5, which are currently visible and hence the wrong child are getting updated.

Any other way to handle this?

LeHaine :

You need to use your RecyclerView adapter to grab the child count and to update any children. The adapter requires to override a getItemCount function which should return the total items in the list. Attempting to get the child count or updating a child directly from the RecyclerView is not the correct way.

class TestAdapter(private val data: MutableList<String>) : RecyclerView.Adapter<TestAdapter.ViewHolder>() {
   ...
    override fun getItemCount(): Int {
        return data.size
    }
   ...
}

And to update a child in the your RecyclerView you need to tell the adapter to do that as well. Inside your adapter you can create a method that takes in an index any other necessary data to update a child.

class TestAdapter(private val data: MutableList<String>) : RecyclerView.Adapter<TestAdapter.ViewHolder>() {
    ...
    fun updateChildAt(idx: Int, newValue: String) {
        data[idx] = newValue
        notifyItemChanged(idx)
    }
    ...
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398655&siteId=1