我有一个在片段中成功启动的DatePickerDialog。当方向发生变化时,应用程序崩溃。 logcat输出表明NPE与DatePickerFragment中的onDismiss一起发生。 onDismiss代码用于切换软键盘再次显示(在启动DatePickerDialog后将其切换)。用于启动软键盘的InputMethodManager使用“getActivity()”引用,我认为这是因为重新创建Activity后导致定位后的崩溃。我可以使用findFragmentByTag替换对片段的引用,以便在方向更改时重用对话碎片吗?
这是部分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);
}
}
Activity file // uses show() to launch the DialogFragment:
public class Activity extends AppCompatActivity {
...
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
答案 0 :(得分:1)
检查getActivity()
null
是否不是onDismiss()