【问题标题】:How pass callback from activity to fragment如何将回调从活动传递到片段
【发布时间】:2020-05-21 09:27:41
【问题描述】:

在文档中描述了将数据从片段传递到活动的方法 (https://developer.android.com/training/basics/fragments/communicating.html)。 我有相反的情况,我需要将数据从活动传递到片段。从片段设置回调到活动的最佳方法是什么?我在片段中使用(activity as MainActivity).setCallback(this),它可以工作。

【问题讨论】:

    标签: android kotlin fragment


    【解决方案1】:

    在这种情况下,您的活动不知道片段是否已创建/未销毁。 您可以使用 liveData 实现您想要的。

    在 MainActivity 中:

    class MainActivity: BaseFragmentActivity() {
        val viewModel: CustomViewModel by viewModels()
    
        fun yourFunction() {
            viewModel.dataToPassToFragment.value = yourData
        }
    
    }
    

    视图模型:

    class CustomViewModel: ViewModel() {
        var dataToPassToFragment = MutableLiveData<String>()
    }
    

    片段:

    class CustomFragment: BaseFragment() {
        override val viewModel: CustomViewModel by activityViewModels()
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
            super.onCreateView(inflater, container, savedInstanceState)
            viewModel.dataToPassToFragment.observe(this, Observer { data ->
                // do what you want with this data
            })
        }
    }
    

    这样做,您的活动不需要知道片段,如果活动更改数据并且片段被销毁,您将不会发生任何崩溃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多