将参数从活动传递到片段时,参数将丢失。
活动:
public class DatePickerFragmentActivity extends AppCompatActivity {
private static final String EXTRA_CRIME_DATE = "CRIME_DATE";
private Date mCrimeDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
mCrimeDate = (Date) getIntent().getSerializableExtra(EXTRA_CRIME_DATE);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
private Fragment createFragment(){
return DatePickerFragment.newInstance(mCrimeDate);
}
}
这时,片段仍然有束中的数据,由调试器检查。
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
片段:
public class DatePickerFragment extends DialogFragment {
private static final String ARG_DATE = "date";
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(ARG_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDate = (Date) getArguments().getSerializable(ARG_DATE);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_date, container, false);
}
}
但是在这个地方,捆绑包已经是空的:
mDate = (Date) getArguments().getSerializable(ARG_DATE);
我的应用程序的布局如下:
ListView活动/片段-> ViewPager活动/片段-> DatePicker活动/片段