我正在使用以下方法弹出对话框以选择日期。
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 岁,我需要提醒用户。我试过上面的代码,但它关闭了对话框并返回到 Activity 。
我想留在对话框中,直到用户选择 18 岁的日期。我不确定如何在对话框中获取 onclick 事件?
最佳答案
您正在使用的日期选择器对话框已弃用,因此我建议您不要使用它。
您可以通过两种方式(据我所知)实现日期选择器
- 使用 DialogFragment
- 使用警报对话框
使用 DialogFragment:
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);
}
}
检查此示例并在您的 Activity 中实现相同的示例。
使用警报对话框:
使用第二个非常简单
在你的 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();
关于android - 如何在 DatePickerDialog.OnDateSetListener 中获取 OnClick?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15027454/