简介
在我们开发过程中,经常会遇到需要在fragment间进行数据传递(特别是引入Navigation导航后的单Activity、多Fragment模式),比如常见的在FragmentA更新FragmentB的状态、FragmentA拿到数据传递到FragmentB等等。从 Fragment 1.3.0-alpha04 开始,每个 FragmentManager 都会实现 FragmentResultOwner。这意味着 FragmentManager 可以充当 Fragment 结果的集中存储区,下面主要介绍最新的通过FragmentManager传递数据。
依赖
在app的build.gradle文件中添加依赖:
dependencies {
......
implementation 'androidx.fragment:fragment:1.3.0-alpha07'
}
使用
① 同级Fragment间传递数据
发送方:FragmentB
class FragmentB : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_b, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btn_send.setOnClickListener {
val bundle = bundleOf(
"data" to "我是FragmentB的数据",
"isShow" to true
)
//发送数据
parentFragmentManager.setFragmentResult("sendData",bundle)
}
}
}
接收方:FragmentA
class FragmentA : Fragment(){
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_a, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//接收数据,requestKey必须和发送方的requestKey一致
parentFragmentManager.setFragmentResultListener("sendData", this,
FragmentResultListener { _, result ->
if (result.getBoolean("isShow")) {
tv_a.text = result.getString("data")
}
})
}
}
② 父级和子级Fragment间传递数据
发送方:FragmentB(父级)
class FragmentB : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_b, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btn_send.setOnClickListener {
val bundle = bundleOf(
"data" to "我是FragmentB的数据",
"isShow" to true
)
//发送数据 父级的parentFragmentManager变为childFragmentManager
childFragmentManager.setFragmentResult("sendData",bundle)
}
}
}
接收方:FragmentA(子级)
class FragmentA : Fragment(){
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_a, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//接收数据,requestKey必须和发送方的requestKey一致
parentFragmentManager.setFragmentResultListener("sendData", this,
FragmentResultListener { _, result ->
if (result.getBoolean("isShow")) {
tv_a.text = result.getString("data")
}
})
}
}