Is it possible to pass a variable to the previous fragment from another fragment?

I'm trying to pass a variable back to a previous snippet, similar to startActivityForResult but with snippets. Is it possible?

Code I Used To call the snippet, do the following:

FragmentFullScreen fragment = new FragmentFullScreen();
        Bundle args = new Bundle();
        args.putParcelable(ARG_VIDEO_SELECTED, mVideoSelected);
        fragment.setArguments(args);

getFragmentManager().beginTransaction()
                .replace(R.id.container, FragmentFullScreen.newInstance(mVideoSelected))
                .addToBackStack("FragmentDetails")
                .commit();

      

And then I use popBackStack to go to the previous snippet:

getFragmentManager().popBackStack();

      

And there is when I want to update a variable from the previous snippet.

+3


source to share


4 answers


Communication between fragments must be done through an action. And to achieve this communication between fragment and activity, this is the best way http://developer.android.com/guide/topics/fundamentals/fragments.html#CommunicatingWithActivity .



0


source


You can implement an Observable in your first snippet and create an Observer that can be used in conjunction with the Application or Activity class.

Then in the second snippet you will get this Observer from the application and update the data. If the 1st snippet still exists, your variable will be passed there.



http://developer.android.com/reference/java/util/Observer.html http://developer.android.com/reference/java/util/Observable.html

+1


source


Bundle args = new Bundle();
args.putParcelable(ARG_VIDEO_SELECTED, mVideoSelected);
fragment.setArguments(args);

      

Place this variable in "args" (key value map only). As well as:

args.putExtra("id", id);
args.putExtra("parcelable", p)

      

0


source


A cool way to do this is to create a singleton class:

public class Singleton {

private static Singleton mInstance = null;

private int mVar;

private Singleton() {

if (mInstance == null) {

    mInstance = new Singleton();
}

return mInstance;

}

public static getInstance () {
    return mInstance;
}

public int getVar () {

return mVar;
}

public void setVar (int val) {
 mVar = val;
}

}

      

-2


source







All Articles