Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables with Android fragmentmanager [duplicate]

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();
like image 545
J.J. Avatar asked Jan 06 '23 13:01

J.J.


1 Answers

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);
        }
    }
}
like image 66
W0rmH0le Avatar answered Jan 31 '23 01:01

W0rmH0le