当父按钮的 onClick 时,从 ChildFragment 与 Parent 通信 [英] Communicate from ChildFragment to Parent when parent button's onClick
问题描述
我有一个父 Fragment
,它有一个 FragementContainerView
,其中有不同 Fragment 的转换.parentFragment 有一个按钮,单击该按钮时,它必须从容器视图内的不同子片段中收集所有数据.我正在使用 Navigation
组件和 FragmentResultAPI
,第一个用于片段导航/转换,最后一个用于从子级到父级获取结果.我知道如何将孩子的数据返回给父母,但我不知道如何通知孩子将数据发回.我发现了这个:
I have a parent Fragment
that has inside a FragementContainerView
in which there is a transition of different Fragments. The parentFragment has a button that when is clicked it has to collect all the data from the different children fragments inside the container view. I am using Navigation
component and FragmentResultAPI
, the first for the fragment navigation/transition and the last for getting the results from the children to the parent. I know how to return back the data from the children to the parent, but I do not know how to notify the children to send the data back. I've found this:
View view = inflater.inflate(R.layout.parent_fragment, container, false);
MyFirstChildFragment fragment = (MyFirstChildFragment) getChildFragmentManager().findFragmentById(R.id.child_fragment_id);
fragment.heyChildrenGiveMeYourDataBack(); //on Button click listener
我知道这是传统方式,但我想知道有没有更现代的方式,或者我们称之为导航方式.
I know this is the traditional way, but I was wondering there was a more modern way or, let's call it, a Navigation way.
父片段属于 main_graph_nav
,但所有子片段都属于不同的 nested_graph_nav
.所以我有一个作用域 ViewModel
来在孩子之间共享数据,但仍然不知道如何通知孩子将数据发送回父母.
The parent fragment belongs to the main_graph_nav
but all children belong to a different nested_graph_nav
. So I have a scoped ViewModel
to share the data between the children but still no idea how to notice the children to send the data back to the parent.
推荐答案
我最终决定在子代码中搜索父级的 FragmentManager 以便通过调用来设置 Fragment 结果:
I finally decided to search the FragmentManager of the parent in the child's code in order to set the Fragment result by calling:
getParentFragment().getParentFragmentManager().setFragmentResult...
在父代码中通过以下方式获取结果:
and inside the parent's code get the result by:
getChildFragmentManager().setFragmentResultListener...
这篇关于当父按钮的 onClick 时,从 ChildFragment 与 Parent 通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!