Reputation: 2235
I use ListAdapter as the source of a RecyclerView, it will display a list of MVoice
. You can see Code B.
I think I can get the position of a MVoice
in ListAdapter, so I can scroll to the position of the item in RecyclerView, just like Code A
Is there a way to get the position of a Movice
?
Code A
binding.recyclerViewVoice.adapter = myAdapter
mHomeViewModel.listVoiceBySort.observe(this.viewLifecycleOwner) {
myAdapter.submitList(it)
}
//val position=myAdapter.getPostionByItem(aMovice)
//binding.recyclerViewVoice.scrollToPosition(position)
Code B
class VoiceAdapters (private val aHomeViewModel: HomeViewModel, private val mPlay: PlayInterface):
ListAdapter<MVoice, VoiceAdapters.VoiceViewHolder>(MVoiceDiffCallback()) {
private lateinit var mContext: Context
private lateinit var mLifecycleOwner:LifecycleOwner
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VoiceViewHolder {
mContext = parent.context
mLifecycleOwner = mContext as LifecycleOwner
return VoiceViewHolder(
LayoutVoiceItemBinding.inflate(LayoutInflater.from(parent.context), parent, false).also {
it.lifecycleOwner = mLifecycleOwner
it.aHomeViewModel = aHomeViewModel
}
)
}
override fun onBindViewHolder(holder: VoiceViewHolder, position: Int) {
val inputMVoice = getItem(position)
holder.bind(inputMVoice)
}
inner class VoiceViewHolder (private val binding: LayoutVoiceItemBinding):
RecyclerView.ViewHolder(binding.root) {
fun bind(inputMVoice: MVoice) {
binding.amVoice = inputMVoice
binding.executePendingBindings()
}
}
}
class MVoiceDiffCallback : DiffUtil.ItemCallback<MVoice>() {
override fun areItemsTheSame(oldItem: MVoice, newItem: MVoice): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: MVoice, newItem: MVoice): Boolean {
return oldItem == newItem
}
}
Upvotes: 0
Views: 1722
Reputation: 1001
You can get a reference to the list currently displayed with currentList
, and use indexOf()
to get the position
fun getPositionByItem(aMovice: MVoice) = currentList.indexOf(aMovice)
Upvotes: 2
Reputation: 755
Add a ItemClick Listener in fun bind(), then pass the MVoice.getPosition in Toast.
Thus you would able to see the position of item in your toast.
Upvotes: 0