我有一个在片段中成功启动的DatePickerDialog。当方向发生变化时,应用程序崩溃。 logcat输出表明NPE与DatePickerFragment中的onDismiss一起发生。 onDismiss代码用于切换软键盘再次显示(在启动DatePickerDialog后将其切换)。当我删除onDismiss代码时,应用程序不再崩溃。我在这里缺少什么?
这是部分DatePickerFragement文件:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
public DatePickerFragment() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
DatePickerDialog picker = new DatePickerDialog(getActivity(),
this, year, month, day);
return picker;
}
public void onDismiss(final DialogInterface dialog) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(CardViewActivity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
super.onDismiss(dialog);
}
}
这是我有另一个处理方向更改的片段,没有崩溃和键盘切换正确:
public class CreateSkycardFragment extends DialogFragment {
public CreateSkycardFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.skyfrag_layout, container, false);
getDialog().setTitle("Delete card");
Button btnCancel = (Button) rootView.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(CardViewActivity.INPUT_METHOD_SERVICE);
// The soft keyboard always closes when the DialogFragment is displayed. So the
// line below toggles the soft keyboard to show again.
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
// The line below cancels the dialog box.
getDialog().cancel();
}
});
// When the user clicks "OK" to delete for the "Delete skycard" dialog.
Button btnOK = (Button) rootView.findViewById(R.id.btnOK);
btnOK.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Next line dismisses the DialogFragment
dismiss();
// Next line returns to the previous activity (MainActivity) by closing
// the current activity (CardViewActivity).
getActivity().finish();
}
});
getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(android.content.DialogInterface dialog, int keyCode, KeyEvent event) {
if ((keyCode == android.view.KeyEvent.KEYCODE_BACK)) {
if (event.getAction()!= KeyEvent.ACTION_DOWN)
// Next line dismisses the dialogfragment
dismiss();
// Next line returns to the previous activity (MainActivity) by closing the fragment and
// the current activity (CardViewActivity).
getActivity().finish();
return true;
}
return false;
}
});
return rootView;
}
}
答案 0 :(得分:0)
看到问题是你启动了一个Activity并且你有一些变量。
旋转屏幕时,您使用变量销毁了该活动。
现在,当您到达onDismiss
时,您正试图解除已在轮换更改时销毁的值。
您可以尝试制作变量static
。
所以它变成了'staticvariable' .dismissDialog()。