将数据从 Fragment 发送到 MainActivity
我的 MainActivity
中有一个 TextView
和一个 Button
,它位于 Fragment
附加到 主活动代码>.当我单击 Button
时,我希望 TextView
说,Button Clicked".
I have a TextView
in my MainActivity
and a Button
which is in a Fragment
attached to the MainActivity
. When I click the Button
I want the TextView
to say, "Button Clicked".
这可能吗?
我知道附加到同一个 Activity
的两个 Fragment
可以轻松地相互通信并相互发送数据.但是Fragment
中的对象可以向Activity
I know two Fragments
attached to the same Activity
can easily communicate with each other and send data to each other. But can an object in the Fragment
send data to an object in an Activity
让 TextView
成为自己的 Fragment
并将其附加到 Activity
是否更好的编程?然后我可以简单地让两个片段相互发送数据.
Is it better programming to make the TextView
its own Fragment
and attach it to the Activity
? Then I can simply have the two fragments send data to each other.
抱歉,如果这不是 StackOverflow 的正确问题类型.我是 Fragments
的新手,无法找到有关此问题的明确解释.
Sorry if this isn't a proper type of question for StackOverflow. I am new to Fragments
and have not been able to find a clear explanation on this issue.
提前致谢!
当前接受的答案(在 Activity 中使用静态方法)既奇怪又可以说是错误的".
The currently accepted answer (to use a static method in the Activity) is both odd and arguably "wrong".
静态方法的使用很奇怪,因为它不需要是静态的.
The use of the static method is odd because there's just no need for it to be static.
这是错误的,因为 Fragment 必须知道它所在的特定 Activity.这是紧耦合",也使得片段不可重用.
It's wrong because the Fragment must have knowledge of the particular Activity in which it is hosted. This is "tight coupling", and also makes it so that the fragment is not re-usable.
这个问题有两种常见的解决方案:
There are two common solutions to this issue:
- 创建一个接口,其中包含 Activity 中可以被片段调用的方法.在Activity中实现该接口(所有使用该片段的Activity),然后在Fragment中,使用getActivity()获取该Activity,并将其转换为该接口.在这种模式中,通常还会检查(使用instanceof")Activity 是否实现了接口,如果没有则抛出 RuntimeException.
- 使用事件总线(例如 Square 的 Otto、GreenRobot 的 EventBus)在 Fragment 与其父 Activity 之间进行通信.我觉得这是最干净的解决方案,并且完全抽象了来自它的 Activity 的片段.