Skip to content Skip to sidebar Skip to footer

How To Pass Variables With Android Fragmentmanager

I have the following simple code to switch from one fragment to another in the content frame. Is there a simple way to pass variables in the following code? FragmentManager fm = ge

Solution 1:

You can use Bundle:

FragmentManager fm = getActivity().getFragmentManager();
Bundlearguments = newBundle();
arguments.putInt("VALUE1", 0);
arguments.putInt("VALUE2", 100);

MyFragment myFragment = newFragment();
fragment.setArguments(arguments);

fm.beginTransaction().replace(R.id.content_frame, myFragment).commit();

Then, you retrieve as follows:

publicclassMyFragmentextendsFragment {

    publicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundlebundle=this.getArguments();
        if (bundle != null) {
            intvalue1= bundle.getInt("VALUE1", -1);
            intvalue2= bundle.getInt("VALUE2", -1);
        }
    }
}

Solution 2:

How about creating a parameterized constructor for TransactionDetailsFragment?

fm.beginTransaction().replace(R.id.content_frame, new TransactionDetailsFragment(YOUR_PARAMS)).commit();

When you create new TransactionDetailsFragment(YOUR_PARAMS) as a param of FragmentTransaction, I think using constructor is a good choice.

Solution 3:

Or you could use the newInstance method - create a method inside your Fragment class like:

publicstatic TransactionDetailsFragment newInstance(String param) {
    TransactionDetailsFragmentfrag=newTransactionDetailsFragment();
    Bundlebund=newBundle();
    bund.putString("paramkey", param); // you use key to later grab the value
    frag.setArguments(bund);
    return frag;
}

So to create your fragment you do:

TransactionDetailsFragment.newInstance("PASSING VALUE");

(This is used instead of your new TransactionDetailsFragment() )

Then for example in onCreate/onCreateView of the same fragment you get the value like this:

Stringvalue= getArguments().getString("paramkey");

Post a Comment for "How To Pass Variables With Android Fragmentmanager"