android – 片段已添加:DateDialog

我已将editText设为可点击.单击它后,将显示DatePicker对话框.

 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.information);
 date = (EditText) findViewById(R.id.date);
 dialog=new DateDialog();
 date.setOnClickListener(this);

        public void onClick(View arg0) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        dialog.show(ft, "DatePicker");
        }

 public static class DateDialog extends android.app.DialogFragment implements DatePickerDialog.OnDateSetListener {
        public DateDialog() {}

         public Dialog onCreateDialog(Bundle savedInstanceState)
        {
            final Calendar c=Calendar.getInstance();
            int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH);
            int day=c.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(),this,year,month,day);
        }

        public void onDateSet(DatePicker view,int year, int month, int day)
        {
            String date1=day+"-"+(month+1)+"-"+year;
            date.setText(date1);
            date2= date.getText().toString();
            return ;
         }
    }

如果我不小心双击editText,应用程序崩溃并显示Fragment已添加错误,如下所示.

11-26 10:16:04.745    2348-2348/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.project.myapplication, PID: 2348
    java.lang.IllegalStateException: Fragment already added: DateDialog{d1ca446 #0 DatePicker}
            at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1219)
            at android.app.BackStackRecord.run(BackStackRecord.java:715)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
            at android.app.FragmentManagerImpl$1.run(FragmentManager.java:482)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

有谁知道如何解决这一问题 ?谢谢

解决方法:

the app crashed and shows Fragment already added error as below

因为打电话给show方法.检查是否显示对话框,如果显示然后丢弃点击事件,否则显示对话框:

Dialog dialogFrg=dialog.getDialog();
if(dialogFrg!=null && dialogFrg.isShowing()) {
   // no need to call dialog.show(ft, "DatePicker");
} else {
   // call dialog.show(ft, "DatePicker");
}

或者使用也可以使用像开关一样的布尔标志,通过使标志为true / false来检查对话框是否显示.

上一篇:element ui DatePicker 禁用当前日之前的时间


下一篇:关于jquery-ui的datepicker使用