片段间通信是否适用于嵌套片段? [英] Inter-fragment communication applied to Nested Fragments?
问题描述
Android开发者网站上有很棒的文章之间进行通信的接口:
The Android developers site has a great article on how to use interfaces to communicate between:
- 一个
Fragment
及其托管的Activity
- 由同一
Activity
托管的两个
Fragment
我正在努力将此概念应用于嵌套片段.特别是, getActivity()
或 Fragment#onAttach(Activity)
会告诉您什么 Activity
承载了 Fragment
.
I am struggling to apply this concept to nested fragments. In particular, getActivity()
or Fragment#onAttach(Activity)
tell you what Activity
is hosting a Fragment
.
在嵌套片段的情况下等效的是什么?子" Fragment
如何知道其包含在父" Fragment
中?而且,在不知道这一点的情况下,子 Fragment
如何将事件传递到其父 Fragment
?
What is the equivalent in case of nested fragments? How does a "child" Fragment
know what "parent" Fragment
it is included in? And without knowing this, how can a child Fragment
pass events up to its parent Fragment
?
一种明显的方法是从子 Fragment
广播意图,并让父 Fragment
监听广播,但是我宁愿使用 interface
为基础的方法.
An obvious way is to broadcast intents from the child Fragment
and have the parent Fragment
listen for the broadcast, but I'd rather use the interface
-based approach.
推荐答案
It turns out there is a getParentFragment() method introduced to cater to nested fragments. It is available on android.app.Fragment
from API 17, but can be used on older versions using android.support.v4.app.Fragment
.
我不敢相信我忽略了这个API!
I can't believe I overlooked this API!
我碰到了此要点,该过程可以弄清楚父组件(是否 Fragment
或 Activity
)简单,优雅且安全!
I came across this gist that makes this process of figuring out the parent component (whether Fragment
or Activity
) easy, elegant and safe!
这篇关于片段间通信是否适用于嵌套片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!