如何使用Android fragmentmanager传递变量

J.J*_*.J. 2 android android-fragments fragmentmanager

我有以下简单的代码在内容框架中从一个片段切换到另一个片段.是否有一种简单的方法可以在以下代码中传递变量?

FragmentManager fm = getActivity().getFragmentManager();

fm.beginTransaction().replace(R.id.content_frame, new TransactionDetailsFragment()).commit();
Run Code Online (Sandbox Code Playgroud)

W0r*_*0le 5

你可以使用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();
Run Code Online (Sandbox Code Playgroud)

然后,您检索如下:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)