Reputation: 35
I have a recyclerView in my kotlin app that shows a list of items, when i click on one my app navigates to other fragment that shows the details of that recyclerview item, my problem is when I filter the results, it uses the adapterPosition that in this case, its different from the position of the data in the json.
When I filter the data with searchView, I submit to the adapter the new list with the filters applied.
Fragment where the recyclerview is: (Here i would like to send as a string one of the fields shown in the recyclerview item i click)
private var museumsListAdapter=MuseumsListAdapter{ it ->
val bundle = Bundle().apply {
putInt(INDICE,it)
}
findNavController().navigate(R.id.action_ListMuseumsFragment_to_detailsMuseumFragment, bundle)
}
Adapter of the recyclerView:
class MuseumsListAdapter(private val onMuseumSelected: (Int) -> Unit):
ListAdapter<MuseumsFieldsItem, MuseumsListViewHolder>(MuseumsFieldsItem.DIFF_CALLBACK) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MuseumsListViewHolder {
val itemView=MuseumListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MuseumsListViewHolder(itemView.root){
onMuseumSelected(it)
}
}
override fun onBindViewHolder(holder: MuseumsListViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
ViewHolder of the recyclerview:
lass MuseumsListViewHolder(itemView: View, private val onItemClicked: (Int) ->Unit) : RecyclerView.ViewHolder(itemView) {
val itemBinding=MuseumListItemBinding.bind(itemView)
init {
itemView.setOnClickListener{
onItemClicked(adapterPosition)
}
}
And in the other fragment (details one) I get the value "INDICE" of the bundle.
Upvotes: 0
Views: 188
Reputation: 8191
class MuseumsListAdapter(private val onMuseumSelected: (Int) -> Unit):
this is a callback which takes in an int, so just don't use int :)
class MuseumsListAdapter(private val onMuseumSelected: (Foo) -> Unit):
where Foo represents whatever you model is, make use of Museum in your case
inside your:
itemView.setOnClickListener{
onMuseumSelected(adapterPosition)
}
you now need an instance of your Museum class.
by using private val onMuseumSelected: (Foo) -> Unit
you'll get back a complete model to your fragment/activity, so you can use whatever field you need
Upvotes: 2