Reagan Gallant Reagan Gallant - 1 month ago 10
Android Question

Display timerpickerdialog within a fragment using Xamarin Android

I have followed the xamarin Timepicker tutorial link to create a

Timepickerdialog
within an
Activity
. It works great.

I need to to do the same in a
fragment
but have failed to make it work.
Can someone please show me how to do it using a fragment? Any guildelines or links or advice.

I'm using
Xamarin Andriod
.
Thank you in advanced.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/timeDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<Button android:id="@+id/pickTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change the time"/>
</LinearLayout>


MainActivity.cs

private TextView time_display;
private Button pick_button;
private int hour;
private int minute;
const int TIME_DIALOG_ID = 0;

protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);

// Set our view from the "Main" layout resource
SetContentView (Resource.Layout.Main);

// Capture our View elements
time_display = FindViewById<TextView> (Resource.Id.timeDisplay);
pick_button = FindViewById<Button> (Resource.Id.pickTime);

// Add a click listener to the button
pick_button.Click += (o, e) => ShowDialog (TIME_DIALOG_ID);

// Get the current time
hour = DateTime.Now.Hour;
minute = DateTime.Now.Minute;

// Display the current date
UpdateDisplay ();
}

// Updates the time we display in the TextView
private void UpdateDisplay ()
{
string time = string.Format ("{0}:{1}", hour, minute.ToString ().PadLeft (2, '0'));
time_display.Text = time;
}

private void TimePickerCallback (object sender, TimePickerDialog.TimeSetEventArgs e)
{
hour = e.HourOfDay;
minute = e.Minute;
UpdateDisplay ();
}

protected override Dialog OnCreateDialog (int id)
{
if (id == TIME_DIALOG_ID)
return new TimePickerDialog (this, TimePickerCallback, hour, minute, false);

return null;
}


Fragment.cs

//Everything same as Activity
//updated the following:

time_display = view.FindViewById<TextView>(Resource.Id.timeDisplay);
pick_button = view.FindViewById<Button>(Resource.Id.pickTime);

protected override Dialog OnCreateDialog(int id)
{
if (id == TIME_DIALOG_ID)
return new TimePickerDialog(this.Activity, TimePickerCallback, hour, minute, false);

return null;
}


Result:

Error 1.The name 'ShowDialog' does not exist in the current context.

Error 2.Fragement.OnCreateDialog(int)': no suitable method found to override.

Answer

Try this set of code to show the TimePickerDialog.

TimePickerDialog timePickerDialog = new TimePickerDialog(this.Activity, TimePickerCallback, hour, minute, false);
                timePickerDialog.Show();
Comments