我想将活动中的数据传递给它管理的片段。 我一直在尝试下面的代码: 活动代码:
String accountNumber = getIntent().getStringExtra("accountNumber").toString();
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("accountNumber", accountNumber);
fragment.setArguments(bundle);
onCreateView方法中的片段代码:
Bundle args = getArguments();
if (args != null && args.containsKey("accountNumber")) {
accountNumber = args.getString("accountNumber").toString();
Toast toast = Toast.makeText(getActivity(), accountNumber, Toast.LENGTH_SHORT);
toast.show();
}
我使用Intent.getExtra获得的String accountNumber不为null,但是当我将它传递给片段时,accountNumber结果为null ...
我也尝试在活动类中使用FragmentManager,如下所示:
public void onCreate(Bundle savedInstanceState) {
// ...
if (savedInstanceState == null) {
FragmentManager fragmentManager = getFragmentManager()
// Or: FragmentManager fragmentManager = getSupportFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("accountNumber", accountNumber);
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
答案 0 :(得分:0)
检查什么样的" Fragment"你在活动中导入了吗?您可以导入并实例化" android.app.Fragment"期待参数在你的" com.my.application.Fragment"中神奇地展示。