[英]Sending data from Fragment to MainActivity
I have a TextView
in my MainActivity
and a Button
which is in a Fragment
attached to the MainActivity
. 我的
MainActivity
有一个TextView
,而在与MainActivity
相连的Fragment
中有一个Button
。 When I click the Button
I want the TextView
to say, "Button Clicked". 当我单击
Button
我希望TextView
说“按钮已单击”。
Is this possible? 这可能吗?
I know two Fragments
attached to the same Activity
can easily communicate with each other and send data to each other. 我知道,连接到同一
Activity
两个Fragments
可以轻松地相互通信并相互发送数据。 But can an object in the Fragment
send data to an object in an Activity
但是
Fragment
的对象可以将数据发送到Activity
的对象Activity
Is it better programming to make the TextView
its own Fragment
and attach it to the Activity
? 使
TextView
其自己的Fragment
并将其附加到Activity
是更好的编程方法吗? Then I can simply have the two fragments send data to each other. 然后,我可以简单地让两个片段相互发送数据。
Sorry if this isn't a proper type of question for StackOverflow. 抱歉,如果这不是StackOverflow的正确类型。 I am new to
Fragments
and have not been able to find a clear explanation on this issue. 我是
Fragments
新手,因此无法在此问题上找到清晰的解释。
Thanks in advance! 提前致谢!
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. 静态方法的使用很奇怪,因为它不需要是静态的。
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: 有两种常见的解决方案:
You can create a static method inside your Activity which will have the TextView inside it. 您可以在Activity中创建一个静态方法,该方法中将包含TextView。 And when you need updatation just call it from fragment.
而当您需要升级时,只需从片段中调用它即可。 something like:
就像是:
In Activity: 活动中:
public static void updateText(){
//your textview
text.setText("Button Clicked");
}
Just call it when you will click on the Button from fragment. 当您单击片段中的按钮时,只需调用它即可。
something like: 就像是:
From Fragment: 从片段:
//Inside Button click listener
MainActivity.updateText();
Not tested, but hope this approach will work. 尚未测试,但希望这种方法能奏效。
Have you tried the getActivity()
method to retrieve a reference to the parent activity and use a method to set the data, something like: 您是否尝试过
getActivity()
方法来检索对父活动的引用并使用一种方法来设置数据,例如:
// public final Activity getActivity ()
MyActivity activity = (MyActivity) getActivity();
activity.setText("...");
I may be wrong but I would try that. 我可能是错的,但我会尝试的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.