[英]Set the limit on selection of a year in DatePickerDialog in xamarin.android
我是Xamarin.android的新手。在我的項目中,我在xamarin.android中使用DatePickerDialog。 我想對年份的選擇設定限制。 我的意思是說,我必須將Dob的年齡限制設置為21歲。 因此,不允許用戶選擇從當前日期開始超過21歲的年齡。即,如果當前年份為2017年,則不應允許用戶選擇1996年以后的年齡。選擇1996年以后的年份,應該再次回到1996年。
在單擊edittext時,我正在調用DatePickerFragment類。 所以這是我使用的代碼。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace MobileApplication.Droid
{
public class DatePickerFragment : DialogFragment,
DatePickerDialog.IOnDateSetListener
{
// TAG can be any string of your choice.
public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();
// Initialize this value to prevent NullReferenceExceptions.
Action<string> _dateSelectedHandler = delegate { };
public static DatePickerFragment NewInstance(Action<string> onDateSelected)
{
DatePickerFragment frag = new DatePickerFragment();
frag._dateSelectedHandler = onDateSelected;
return frag;
}
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
DateTime currently = DateTime.Now;
DatePickerDialog dialog = new DatePickerDialog(Activity,
this,
currently.Year - 21,
currently.Month,
currently.Day);
dialog.DatePicker.MaxDateTime.DayOfYear.Equals(currently.Year - 21);
return dialog;
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
// Note: monthOfYear is a value between 0 and 11, not 1 and 12!
//DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
string selectedDate = (monthOfYear + 1).ToString().PadLeft(2, '0') + "/" + (dayOfMonth).ToString().PadLeft(2, '0') + "/" + year.ToString();
//Log.Debug(TAG, selectedDate.ToLongDateString());
Log.Debug(TAG, selectedDate);
_dateSelectedHandler(selectedDate);
}
}
}
單擊edittext時,年份將設置為(當前年份-21)。 但是用戶不限於在該年之后選擇..如何實現這一年。
DateTime currently = DateTime.Now;
DatePickerDialog dialog = new DatePickerDialog(this, delegate { }, currently.Year -21, currently.Month-1, currently.Day);
dialog.DatePicker.MaxDate = (long)DateTime.Now.AddYears(-21)
.ToUniversalTime()
.Subtract(DateTime.MinValue.AddYears(1969))
.TotalMilliseconds;
dialog.Show();
因此,根據此Link ,通過進行一些小的更改,日期選擇器可以正常工作。 我的意思是現在不允許用戶選擇超過21年的時間。
這些就是我對以前的代碼所做的更改。
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
DateTime currently = DateTime.Now;
DatePickerDialog dialog = new DatePickerDialog(Activity,
this,
currently.Year - 21,
currently.Month,
currently.Day);
dialog.DatePicker.MaxDate = new Java.Util.Date().Time - 662300000000; // 662300000000 => 1 year is converted to milliseconds..
return dialog;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.