我需要将参数传递给我的 fragment ,但 getArguments() 总是返回 null
public static PersonFragment newInstance(int columnCount, ArrayList<Person> personenListe) {
PersonFragment personFragment = new PersonFragment();
Bundle args = new Bundle();
args.putSerializable("persList",personenListe);
args.putInt(ARG_COLUMN_COUNT, columnCount);
personFragment.setArguments(args);
return new PersonFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) { //getAguments() == null !!
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
mPersonenListe = (ArrayList<Person>) getArguments().getSerializable("persList");
}
}
我在 MainActivity
中调用它
openFragment(PersonFragment.newInstance(personenListe.size(), personenListe));
用这个方法
public void openFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
最佳答案
您返回的不是您设置参数的 fragment ,而是一个全新的 fragment 。
因此将 newInstance
更改为:
public static PersonFragment newInstance(int columnCount, ArrayList<Person> personenListe) {
PersonFragment personFragment = new PersonFragment();
Bundle args = new Bundle();
args.putSerializable("persList",personenListe);
args.putInt(ARG_COLUMN_COUNT, columnCount);
personFragment.setArguments(args);
// return new PersonFragment();
return personFragment ; // <<< change here
}
关于android - getArguments() 在 Fragment 中总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65545655/