Reputation: 3964
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".
Is this possible?
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
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.
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.
Thanks in advance!
Upvotes: 0
Views: 1416
Reputation: 30088
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:
Upvotes: 4
Reputation: 5150
You can create a static method inside your Activity which will have the TextView inside it. 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.
Upvotes: 1
Reputation: 76
Have you tried the getActivity()
method to retrieve a reference to the parent activity and use a method to set the data, something like:
// public final Activity getActivity ()
MyActivity activity = (MyActivity) getActivity();
activity.setText("...");
I may be wrong but I would try that.
Upvotes: 0