Android Kotlin – How do I assign a name function in main activity class to setOnClickListener in another class?

huangapple go评论62阅读模式
英文:

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&lt;MyAdapter.ViewHolder&gt;() {
  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&lt;MyAdapter.ViewHolder&gt;() {
     ....
     ....
     holder.itemView.setOnClickListener {
         listener.OnViewItemClicked()
     }
     ....
 }

Explanation -
This is done with the help of kotlin lambda , i.e, equivalent to :-

val clickLambda: (View) -&gt; Unit = {
    listener.OnViewItemClicked()
}

Edit :- Instead of doing this you can directly pass in a lambda of type (View) -&gt; Unit from the activity !

huangapple
  • 本文由 发表于 2020年1月6日 16:29:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定