How to pass variables with Android fragmentmanager

2019-07-22 06:48发布

问题:

This question already has an answer here:

  • How to pass a variable from Activity to Fragment, and pass it back? 5 answers

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();

回答1:

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);
        }
    }
}


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



回答3:

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");