user2456977
user2456977

Reputation: 3964

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. 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

Answers (3)

GreyBeardedGeek
GreyBeardedGeek

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:

  1. Create an interface containing the methods in the Activity that can be called by the fragment. Implement that interface in the Activity (all Activities that use the fragment), and then in the Fragment, use getActivity() to get the Activity, and cast it to the interface. In this pattern, one also typically checks (using 'instanceof') whether the Activity implements the interface, and throws a RuntimeException if it does not.
  2. Use an Event Bus (e.g. Square's Otto, GreenRobot's EventBus) to communicate between the Fragment and it's parent Activity. I feel that this is the cleanest solution, and completely abstracts the Fragment from it's Activity.

Upvotes: 4

Ranjit
Ranjit

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

d311404
d311404

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

Related Questions