MainActivity 代码:
public class MainActivity : Activity { TextView _dateDisplay; Button _dateSelectButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); _dateDisplay = FindViewById<TextView>(Resource.Id.date_display); _dateSelectButton = FindViewById<Button>(Resource.Id.date_select_button); _dateSelectButton.Click += DateSelect_OnClick; } void DateSelect_OnClick(object sender, EventArgs eventArgs) { DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime time) { _dateDisplay.Text = time.ToLongDateString(); }); frag.Show(FragmentManager, DatePickerFragment.TAG); } }
DatePickerFragment.cs 代码:
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<DateTime> _dateSelectedHandler = delegate { }; public static DatePickerFragment NewInstance(Action<DateTime> 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, currently.Month - 1, currently.Day); 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); Log.Debug(TAG, selectedDate.ToLongDateString()); _dateSelectedHandler(selectedDate); } }
Main.axml 代码:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="@dimen/top_padding"> <TextView android:id="@+id/date_display" android:layout_height="wrap_content" android:layout_width="match_parent" android:paddingTop="@dimen/top_padding" android:text="@string/selected_date_text" style="@android:style/TextAppearance.Large" /> <Button android:id="@+id/date_select_button" android:paddingLeft="@dimen/left_padding" android:paddingRight="@dimen/right_padding" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/pick_date_text" android:layout_below="@id/date_display" /> </RelativeLayout>
实现结果:
参考文献:
https://docs.microsoft.com/zh-cn/xamarin/android/user-interface/controls/pickers/date-picker