Hello,
Welcome to our Microsoft Q&A platform!
If you want to create a custom TimePicker
, you don't need to use MessagingCenter
to transfer selected time, and you can achieve IElementController
to get the time from TimePickerDialog.IOnTimeSetListener
like following code, when you new TimePickerDialog
object, you should achieve this IOnTimeSetListener
interface.
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using App68.Droid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(Xamarin.Forms.TimePicker), typeof(MyTimePickerRenderer))]
namespace App68.Droid
{
public class MyTimePickerRenderer : ViewRenderer<Xamarin.Forms.TimePicker, Android.Widget.EditText>, TimePickerDialog.IOnTimeSetListener, IJavaObject, IDisposable
{
TimePickerDialog _dialog;
Context context;
public MyTimePickerRenderer(Context context) : base(context)
{
this.context = context;
}
Context CurrentContext => context;
IElementController ElementController => Element as IElementController;
public void OnTimeSet(Android.Widget.TimePicker view, int hourOfDay, int minute)
{
var time = new TimeSpan(hourOfDay, minute, 0);
Element.SetValue(Xamarin.Forms.TimePicker.TimeProperty, time);
Control.Text = time.ToString(@"hh\:mm");
ClearFocus();
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.TimePicker> e)
{
base.OnElementChanged(e);
SetNativeControl(new Android.Widget.EditText(CurrentContext));
if (Control != null)
{
Control.Click += Control_Click;
Control.FocusChange += Control_FocusChange;
Control.InputType = Android.Text.InputTypes.Null;
if (Element != null && !Element.Time.Equals(default(TimeSpan)))
Control.Text = Element.Time.ToString(@"hh\:mm");
else
Control.Text = DateTime.Now.ToString("HH:mm");
}
}
void Control_FocusChange(object sender, FocusChangeEventArgs e)
{
if (e.HasFocus)
{
ShowTimePicker();
ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true);
}
else
{
ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
}
}
void Control_Click(object sender, EventArgs e) => ShowTimePicker();
void ShowTimePicker()
{
if (_dialog == null)
_dialog = new TimePickerDialog(CurrentContext, this, Element.Time.Hours, Element.Time.Minutes, true);
_dialog.UpdateTime(Element.Time.Hours, Element.Time.Minutes);
_dialog.Show();
}
}
}
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.