触发Kotlin for Android的界面 [英] Triggering an Interface in Kotlin for Android

查看:80
本文介绍了触发Kotlin for Android的界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Kotlin for Android时,有一个特定的接口实现:从片段触发接口。考虑Fragment必须将UI操作传递给父Activity的常见场景。在Java中,我们将定义接口,为其创建侦听器实例,并在接口父节点中实现/覆盖操作。创建一个听众实例对我来说并不那么简单。经过一些谷歌搜索,我找到了一个实现示例,但我不明白为什么它的工作原理。有一个更好的方法吗?为什么必须以下面的方式实现?

There is a specific implementation of interface when it comes to using Kotlin for Android: triggering an interface from a fragment. Consider the common scenario where a Fragment must communicate a UI action to the parent Activity. In Java, we would define the interface, create a "listener" instance of it, and implement/override actions in interface parents. It is the creating a listener instance that is not so straightforward to me. After some googling, I found an implementation example but I do not understand why it works. Is there a better way to do this? Why must it be implemented the way it is below?

    class ImplementingFragment : Fragment(){

  private lateinit var listener: FragmentEvent
  private lateinit var vFab: FloatingActionButton

  //Here is the key piece of code which triggers the interface which is befuddling to me
  override fun onAttach(context: Context?) {
          super.onAttach(context)
          if(context is FragmentEvent) {
              listener = context
          }
      }

    //Notice the onClickListener using our interface listener member variable
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val v: View? = inflater.inflate(R.layout.fragment_layout, container, false)
            vFab = v?.findViewById(R.id.fh_fab)
            vFab.setOnClickListener{listener.SomethingHappened()}
        return v
    }  


}



interface FragmentEvent{
    fun SomethingHappened()
}


推荐答案

在此代码中 lateinit var listener:FragmentEvent 应该初始化,不能 null 。所以 onAttach 应该看起来像

In this code lateinit var listener: FragmentEvent should be initialized and can't be null. So onAttach should looks like

override fun onAttach(context: Context?) {
    super.onAttach(context)
    if (context is FragmentEvent) {
        listener = context
    } else {
        throw RuntimeException(context!!.toString() + " must implement FragmentEvent")
    }
}

在这种情况下如果您忘记在活动中实施 FragmentEvent ,您将收到异常,否则回调已准备好使用。

In this case if you forget to implement FragmentEvent in Activity you'll got an exception, otherwise callback is ready to use.

这篇关于触发Kotlin for Android的界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆