Android Fragment 之间传递数据 - 使用 Bundle
要使用 Bundle 承载数据并在一个 Fragment 中编写方法以转到另一个 Fragment,可以按照以下步骤:
- 在要发送数据的 Fragment 中创建一个 Bundle 对象并将数据添加到它中。
Bundle bundle = new Bundle();
bundle.putString('key', 'value');
- 在要接收数据的 Fragment 中获取 Bundle 对象并从中获取数据。
Bundle bundle = getArguments();
String value = bundle.getString('key');
- 在要转到另一个 Fragment 的方法中创建一个新的 Fragment 对象,并将 Bundle 对象添加到它中。
Fragment fragment = new MyFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
在这个例子中,我们创建了一个名为 'MyFragment' 的新 Fragment 对象,并将 Bundle 对象添加到它中。然后我们获取 FragmentManager 和 FragmentTransaction,并使用 replace() 方法将当前 Fragment 替换为新的 Fragment。最后,我们将此事务添加到 BackStack 中,以便用户可以按返回按钮返回到之前的 Fragment。
注意,这只是一个简单的示例,实际上你可能需要根据你的应用程序的需要进行修改。
原文地址: https://www.cveoy.top/t/topic/oWet 著作权归作者所有。请勿转载和采集!