文章目录
一、前言
在开发中会涉及到Fragment
之间通信的问题。之前的几篇记录了几种方式。这里再记录一种使用接口进行通信的方式。本篇记录Activity
与Fragment
通信的方式。Fragment
与Fragment
之间的通信也可以使用这种方式。以前是使用onAttachFragment()
进行获取Fragment
的添加监听。但是新版的Fragment
使用FragmentOnAttachListener
进行了替换。所以这里使用新版的api。
二、代码演示
Fragment2.kt
class Fragment2 : Fragment() {
var callback: CallBack ?= null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank2, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.fragment1_btn).setOnClickListener {
Log.e("YM","---->callBack是否为null:${null == callback}")
callback?.setResult("ok")
}
}
}
interface CallBack{
fun setResult(value: String)
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
addFragmentListener()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
//添加Fragment时候的监听
private fun addFragmentListener(){
supportFragmentManager.addFragmentOnAttachListener { fragmentManager, fragment ->
if (fragment is Fragment2){
fragment.callback = object : CallBack{
override fun setResult(value: String) {
Log.e("YM","---->接收到Fragment中的数据")
}
}
}
}
}
}
注意:FragmentOnAttachListener
需要在oncreate()
之前调用
这个方式替换了onAttachFragment()
。
三、参考链接
- 与其他 Fragment 通信