I created a recycler view and feed data to it from MyAdapter class, I wanted to get name in recyler view item when it's clicked, On a youtube video I learnt how to get index of item (when clicked). I created an araryList of containing all the names in MyAdapter class, so I can access them it in MainAcitivty class by making a function to return needed arrayList value using index
public fun getName(pos: Int) : String {
return nameList[pos]
}
Now when I tried to call this function on MainActivity class and it shows an error (Unresolved reference: getName)
var name = MyAdapter.getName(position)
I did some searching and couldn't find a solution for this, Can someone help me with properly calling a function in another class (in Kotlin) or a better way to do the same thing and sorry I'm new to Kotlin, Thank you!
CodePudding user response:
in your code getName function is not static So you must get the name like this :
var name = (recyclerView.adapter as MyAdapter).getName(position)
But another way and correct way is to use the callback :
class MyAdapter(val onItemClick: (item: ItemModel?) -> Unit):
RecyclerView.Adapter<YourViewHolder>{
override fun onBindViewHolder(holder: YourViewHolder, position: Int) {
holder.binding.btn.setOnClickListener {
onItemClick.invoke(yourList[position])
}
}
}
Then in your activity or fragment listen to the callback
MyAdapter(){ item ->
}