在Xamarin中在使用Datepicker的时候,一般情况下只需要在对应的按钮或其他控件的点击事件中使用如下语句即可完成:
1 EditText etBirthday = FindViewById<EditText> (Resource.Id.userBirthday); 2 etBirthday.Click += delegate(object sender, EventArgs e) { 3 new DatePickerDialog (this, OnDatePickerSelect, DateTime.Today.Year, DateTime.Today.Month - 1, DateTime.Today.Day).Show(); 4 }; 5 6 void OnDatePickerSelect(object sender, DatePickerDialog.DateSetEventArgs e) 7 { 8 RunOnUiThread(() => 9 { 10 //日期选择之后的操作方法 11 Log.Debug(e.Date.ToString("yyyy-MM-dd")); 12 }); 13 }
但在使用到ActivityGroup时,则可能出现如下错误提示:
Android.Views.WindowManagerBadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@4159dd40 is not valid; is your activity running?
这是因为在使用ActivityGroup的时候是使用到Activity嵌套,使用this获取的不是当前Activity,所以需要将代码修改为如下代码:
1 EditText etBirthday = FindViewById<EditText> (Resource.Id.userBirthday); 2 etBirthday.Click += delegate(object sender, EventArgs e) { 3 new DatePickerDialog (Parent, OnDatePickerSelect, DateTime.Today.Year, DateTime.Today.Month - 1, DateTime.Today.Day).Show(); 4 }; 5 6 void OnDatePickerSelect(object sender, DatePickerDialog.DateSetEventArgs e) 7 { 8 RunOnUiThread(() => 9 { 10 //日期选择之后的操作方法 11 Log.Debug(e.Date.ToString("yyyy-MM-dd")); 12 }); 13 }
如上代码中红色标注,需要将this修改为Parent,以此获取当前Activity,如使用到多层嵌套,则使用多个Parent。