简体   繁体   中英

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

Xamarin provides a complete example of using TimePicker

basically, you need to implement IOnTimeSetListener which has a OnTimeSet method

public void OnTimeSet(TimePicker view, int hourOfDay, int minute)
{
    // hourOfDate and minute are the user's selected values
}

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM