getArguments() 在 Fragment 中总是返回 null

Kam*_*lJu 3 android android-fragments

我需要将参数传递给我的片段,但 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在调用它 MainActivity

openFragment(PersonFragment.newInstance(personenListe.size(), personenListe));
Run Code Online (Sandbox Code Playgroud)

用这个方法

public void openFragment(Fragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.container, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}
Run Code Online (Sandbox Code Playgroud)

Zai*_*ain 7

您没有返回设置参数的片段,而是返回了一个全新的片段。

所以将其更改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 
}
Run Code Online (Sandbox Code Playgroud)