4

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 = getActivity().getFragmentManager();

fm.beginTransaction().replace(R.id.content_frame, new TransactionDetailsFragment()).commit();
J.J.
  • 1,128
  • 2
  • 23
  • 62
  • 2
    No idea why this was marked as dupe, this question clearly says fragmentmanager, the cited answer refers only to a new fragment class., which for a java newb makes a diff. However the accepted answer seems to have acknowledged this correctly. – Mike Purcell Sep 21 '16 at 15:57
  • 1
    Great question, this was exactly what I was looking for, much differently from the "duplicate" marked – E.Akio Aug 08 '19 at 22:01

3 Answers3

8

You can use Bundle:

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

MyFragment myFragment = new Fragment();
fragment.setArguments(arguments);

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

Then, you retrieve as follows:

public class MyFragment extends Fragment {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            int value1 = bundle.getInt("VALUE1", -1);
            int value2 = bundle.getInt("VALUE2", -1);
        }
    }
}
guipivoto
  • 18,327
  • 9
  • 60
  • 75
1

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

 public static TransactionDetailsFragment newInstance(String param) {
    TransactionDetailsFragment frag = new TransactionDetailsFragment();
    Bundle bund = new Bundle();
    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:

String value = getArguments().getString("paramkey");
iBobb
  • 1,140
  • 1
  • 14
  • 35
0

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.

T D Nguyen
  • 7,054
  • 4
  • 51
  • 71
  • Using this, but it has a problem -- without noarg constructor, this fragment cant be used in xml layout. – Pavlus Apr 14 '17 at 09:07