Search code examples
c#androidxamarintimepicker

Get Selected Time from TimePicker in Xamarin Android


Since they said anything that Java can do, C# can do better ...Decided to engineer an alarm app in Xamarin Android and i cant seem to get the value of the selected time in C#...A variable known as triggerTime which should play some music or show an alert dialog when the alarm time matures needs that value... Here is xml for the TimePicker...

 <TimePicker
        android:id="@+id/timePicker1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"/>

Here is the C# code that has the timepicker defined in the AlarmActivity.cs

 base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.Alarm);
     TimePicker timePicker2 = this.FindViewById<TimePicker>(Resource.Id.timePicker1);
//Code to getTime that user selects

Thanks for the help


Solution

  • You could use the TimeChanged event to get the time when the timepicker changed.

    xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TimePicker
        android:id="@+id/timePicker1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/timePicker1"/>
    </RelativeLayout>
    

    Code behind:

      TextView textView = FindViewById<TextView>(Resource.Id.textView1);
            TimePicker timePicker1 = FindViewById<TimePicker>(Resource.Id.timePicker1);
            timePicker1.TimeChanged += delegate
            {
                var h = timePicker1.CurrentHour;
                var m = timePicker1.CurrentMinute;
                textView.Text = h + ":" + m;
    
            };
    

    Screenshot:

    enter image description here