我正在使用DialogFragment在onCreateDialog()中返回DatePickerDialog。我已经将dateSetListener设置为DialogFragment(下面的示例中为“this”),并且一切正常,除了发生屏幕旋转时调用onDateSet()之外,这是不希望的。屏幕旋转时,如何使onDateSet不被调用?
我的DialogFragment
public static class DateDialogFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener{
public static DateDialogFragment newInstance() {
return new DateDialogFragment();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(getActivity(), this, 2012, 11, 19);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
//This is called when screen rotated, which I dont want
Toast.makeText(getActivity(), "Year: "+year+" Month: "+monthOfYear+" Day: "+dayOfMonth, Toast.LENGTH_SHORT).show();
}
}
,这就是我所说的
if(getActivity()!=null){
FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragment newFragment = DateDialogFragment.newInstance();
newFragment.show(fm, "dialog");
}
最佳答案
在onDateSet
方法中,使用Activity::isChangingConfigurations检查是否由于配置更改而重新启动Activity
。如果是,则不显示Toast
。
@Override
public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if( ! this.getActivity().isChangingConfigurations() ) {
// Dialog is dismissed by user explicitly, hence show the Toast message.
Toast.makeText(getActivity(), "Year: "+year+" Month: "+monthOfYear+" Day: "+dayOfMonth, Toast.LENGTH_SHORT).show();
}
}
我已经对其进行了测试,并且效果很好。让我知道是否需要任何进一步的帮助。