Home > Enterprise >  Change data in list for RecyclerView from a single RecyclerView Item
Change data in list for RecyclerView from a single RecyclerView Item

Time:07-20

I want to feed a list of pairs to an a RecyclerView adapter and update the value of this list based on the selection of an individual RecyclerView item.

Let's say I've got a list of pairs, myList, which looks like this:

 val myList:MutableList <Pair<String, Int>> = mutableListOf(
                   //(Hint, Value)
  Pair<String, Int>("Entry 1", 3), 
  Pair<String, Int>("Entry 2", 5),
  // More entries
  Pair<String, Int>("Entry 4", 0),
)

The pair is used to map a hint (or description) of a value to the value itself. This means, that the first value is just used as the hint in a TextInputLayout and the value itself is set as a predefined text in a TextInputEditText (enter image description here

CodePudding user response:

you can get on top of this quite easily actually. all you need to do is to wrap your data that you feed to your recyclerview in live data. then you can observe the live data for any changes and call your adapter with the new data.

CodePudding user response:

Your adapter has the values (it needs to display them, so it has them), so when the user "changes a value" (however it is he does that), the code should just update the value. You can do this in the adapter directly, but a cleaner way to do this is to propagate this up to whatever Activity or Fragment or whatever is controlling the whole process. That code can then update the data with the new values and inform the RecyclerViewAdapter that the data has changed, using notifyDatasetChanged() or notifyItemChanged() or one of the other similar methods.

CodePudding user response:

You have to call adapter.submitList(myList) every time the state of your list changes, passing current myList state. List adapter is using algorithms to compare previous and new state of list, so only objects that had changed will be updated. You can use LiveData class to wrap your list and easily manage variable state, read more about it here: https://developer.android.com/topic/libraries/architecture/livedata

  • Related