英文:
Android Kotlin - How do I assign a name function in main activity class to setOnClickListener in another class?
问题
请检查下面的示例代码和注释,
class MainActivity : AppCompatActivity(), MyListener {
fun OnViewItemClicked(){
// 做一些事情
}
}
class AnotherClass() : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// 如何将此设置为在MainActivity类中声明的OnViewItemClicked?
holder.itemView.setOnClickListener(OnViewItemClicked);
}
}
希望这对你有帮助。
英文:
Please check the sample code and comments below,
class MainActivity : AppCompatActivity(), MyListener {
fun OnViewItemClicked(){
// do something
}
}
class AnotherClass() : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// how do i set this to OnViewItemClicked declared in class MainActivity?
holder.itemView.setOnClickListener(OnViewItemClicked);
}
}
答案1
得分: 3
只需将Listener实例
传递给适配器,如下所示:
val adapter = AnotherClass(this@MainActivity)
然后在适配器中:
class AnotherClass(private val listener: MainActivity): RecyclerView.Adapter<MyAdapter.ViewHolder>() {
// ...
// ...
holder.itemView.setOnClickListener {
listener.OnViewItemClicked()
}
// ...
}
Explanation -
这是通过kotlin lambda
完成的,等同于:
val clickLambda: (View) -> Unit = {
listener.OnViewItemClicked()
}
Edit :- 而不是这样做,您可以直接从活动中传递一个类型为(View) -> Unit
的lambda表达式!
英文:
Just pass the Listener instance
to the adapter:- like :-
val adapter = AnotherClass(this@MainActivity)
Then in adapter
class AnotherClass(private val listener: MainActivity): RecyclerView.Adapter<MyAdapter.ViewHolder>() {
....
....
holder.itemView.setOnClickListener {
listener.OnViewItemClicked()
}
....
}
Explanation -
This is done with the help of kotlin lambda
, i.e, equivalent to :-
val clickLambda: (View) -> Unit = {
listener.OnViewItemClicked()
}
Edit :- Instead of doing this you can directly pass in a lambda of type (View) -> Unit
from the activity !
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论