APagano
APagano

Reputation: 108

How to communicate between a Fragment and an Activity to which it is not attached?

I would like to perform some actions on an Activity after a onClick event on a Fragment.

I only found how to communicate between a fragment and an Activity to which the fragment is attached by using getActivity(), which is NOT my case.

Upvotes: 2

Views: 671

Answers (4)

KISHORE_ZE
KISHORE_ZE

Reputation: 1466

For a super simple solution use the fragment to trigger a method in your activity class that uses an intent to call the activity required.

EDIT: Check the comments below for more help.

Upvotes: 3

Wael Abo-Aishah
Wael Abo-Aishah

Reputation: 942

use delegation: one createView trigger the delegate, and create listener in the activity

try this : Fragment-Fragment communication in Android

just the delegate function

Upvotes: 0

Mibit
Mibit

Reputation: 316

You have to create an interface which your activity implements. BroadcastReceivers do have their advantages but solving this issue with callbacks is straight forward and easy to do.

Here is an example. We give our Activity a String and have it return a Integer:

public interface IMyStringListener{
public Integer computeSomething(String myString);
}

The interface can be defined in the fragment or in a separate file. Next your Activity implement the Interface.

public class MyActivity implements IMyStringListener{

 @Override
 public Integer computeSomething(String myString){
   /** Do something with the string and return your Integer instead of 0 **/ 
   return 0;
  }

}

Then in your fragment you would have a MyStringListener variable and you would set the listener in fragment onAttach(Activity activity) method.

public class MyFragment {

    private MyStringListener listener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            listener = (MyStringListener) activity;
        } catch (ClassCastException castException) {
            /** The activity does not implement the listener. */
        }
    }

}

Upvotes: 0

Sina KH
Sina KH

Reputation: 565

As others said, you have to use broadcasts or services.....

but:

The easiest and fastest way to do it is:

create these two classes::

globals:

public class Globals {

private static final Globals instance = new Globals();
private GlobalVariables globalVariables = new GlobalVariables();

private Globals() {
}

public static Globals getInstance() {
    return instance;
}

public GlobalVariables getValue() {
    return globalVariables;
}

}

and global variables ::

public class GlobalVariables {
    public Activity receiverActivity;
}

not in receiver activity::

Globals.getInstance().getValue().receiverActivity = this;

and sender can do anything now! for example calling a public method from receiver activity:

Globals.getInstance().getValue().doSomething();

It's not recommended basically, but works great. :D

Upvotes: 0

Related Questions