如何在DatePickerDialog.OnDateSetListener中获取OnClick?

时间:2013-02-22 15:24:49

标签: android datepicker

我使用以下方法弹出对话框以选择日期。

private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                dobYear = year;
                dobMonth = monthOfYear;
                dobDay = dayOfMonth;
                if(isEighteenYearOld()){
                   //display the current date
                    dateDisplay();
                } else{
                   Toast.makeText(mContext, "You must be 18 year old", Toast.LENGTH_SHORT).show();
                }  
            } 

        };

我知道onDateSet我们可以获得所选日期。但我正在尝试的是,如果选择的日期小于18年,我需要提醒用户。我已经尝试了上面的代码,但它关闭了对话框并返回到活动。

我想留在对话框中,直到用户选择18岁的日期。我不知道如何在对话框中获取onclick事件?

2 个答案:

答案 0 :(得分:6)

您正在使用的日期选择器对话框已弃用所以我建议您不要使用它...

您可以通过两种方式实现日期选择器(我知道) 1.使用DialogFragment 2.使用AlertDialog

<强>首先

public class MainActivity extends FragmentActivity {
    EditText text;
    Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b=(Button)findViewById(R.id.button1);
        text=(EditText)findViewById(R.id.editText1);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                DateDialogFragment datepicker=new DateDialogFragment();
                datepicker.show(getSupportFragmentManager(), "showDate");
            }
        });
    }

    public class DateDialogFragment extends DialogFragment  implements DatePickerDialog.OnDateSetListener{

        public DateDialogFragment()
        {
        }
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Calendar cal=Calendar.getInstance();
            int year=cal.get(Calendar.YEAR);
            int month=cal.get(Calendar.MONTH);
            int day=cal.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            showSetDate(year,monthOfYear,dayOfMonth);
        }

        }

    public void showSetDate(int year,int month,int day) {
    text.setText(year+"/+"+month+"/"+day);
    }
}

检查此样本并在“活动”中实现相同的内容。

使用警报对话框: 使用第二个非常简单

在res / layout文件夹中创建布局,并将DatePicker放在布局

 LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = (View) inflater.inflate(R.layout.yourlayout, null);
DatePicker picker=(DatePicker)view.findViewById(R.id.datepicker);

  AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
 builder.setView(view).
        builder.setMessage(R.string.dialog_fire_missiles)
               .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // FIRE ZE MISSILES!
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // User cancelled the dialog
                   }
               });
        // Create the AlertDialog object and return it
        return builder.create();

答案 1 :(得分:1)

如果您不想使用此类对话框的自定义实现,则必须子类化DatePickerDialog才能实现此类行为。您无法阻止对话框仅使用DatePickerDialog.OnDateSetListener关闭。

不幸的是,对话框的实现因API级别的不同而不同,因此通过子类化获得所需的行为并非易事。您需要添加一些黑客以使其可靠地工作。

我创建了一个示例实现,阻止对话框关闭,除非设置了适当的日期(或者点击了取消或后退按钮)。调整它以向用户显示警报,最好的位置是onClick()方法中的else分支。

class CheckingDatePickerDialog extends DatePickerDialog {

    private int year;
    private boolean cancel = false;
    private boolean isCancelable = true;

    CheckingDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
        super(context, callBack, year, monthOfYear, dayOfMonth);
        this.year = year;
    }

    CheckingDatePickerDialog(Context context, int theme, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
        super(context, theme, callBack, year, monthOfYear, dayOfMonth);
        this.year = year;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // allow closing the dialog with cancel button
        Button btn = getButton(BUTTON_NEGATIVE);
        if (btn != null) {
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cancel = true;
                    dismiss();
                }
            });
        }
    }

    @Override
    public void setCancelable(boolean flag) {
        isCancelable = false;
        super.setCancelable(flag);
    }

    @Override
    public void onBackPressed() {
        // allow closing the dialog with back button if the dialog is cancelable
        cancel = isCancelable;
        super.onBackPressed();
    }

    private boolean isOldEnough() {
        // test if the date is allowed
        return year <= 1994;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // necessary for some Honeycomb devices
            DatePicker dp = getDatePicker();
            this.year = dp.getYear();
        }

        if (isOldEnough()) {
            // OnDateSetListener is called in super.onClick()
            super.onClick(dialog, which);  
        } else {
            // place your alert here
        }
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int month, int day) {
        // on some Honeycomb devices called only with the first change
        // necessary for devices running Android 2.x
        this.year = year;
        super.onDateChanged(view, year, month, day);
    }

    @Override
    public void dismiss() {
        if (cancel || isOldEnough()) {
            // do not allow the dialog to be dismissed unless a cancel or back button was clicked
            super.dismiss();
        }
    }
};