Jos*_*iro 3 android interface kotlin
在 Android 上使用 Kotlin 时,有一个特定的接口实现:从片段触发接口。考虑 Fragment 必须将 UI 操作传达给父 Activity 的常见场景。在 Java 中,我们将定义接口,创建它的“侦听器”实例,并在接口父项中实现/覆盖操作。创建一个监听器实例对我来说并不那么简单。经过一番谷歌搜索,我找到了一个实现示例,但我不明白它为什么有效。有一个更好的方法吗?为什么必须按照下面的方式实施?
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()
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中lateinit var listener: FragmentEvent应该被初始化,不能被null. 所以onAttach应该看起来像
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is FragmentEvent) {
listener = context
} else {
throw RuntimeException(context!!.toString() + " must implement FragmentEvent")
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果你忘记实现FragmentEventinActivity你会得到一个异常,否则回调就可以使用了。
| 归档时间: |
|
| 查看次数: |
4109 次 |
| 最近记录: |