使用 Xamarin 在片段中显示 timerpickerdialog Android

Display timerpickerdialog within a fragment using Xamarin Android

我按照 xamarin Timepicker 教程 linkActivity 中创建了 Timepickerdialog。效果很好。

我需要在 fragment 中做同样的事情,但未能成功。 有人可以告诉我如何使用片段来做吗?任何准则或链接或建议。

我正在使用 Xamarin Andriod。 先谢谢你了。

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;
}

结果:

错误1.The名称'ShowDialog'在当前上下文中不存在。

错误 2.Fragement.OnCreateDialog(int)': 找不到合适的方法来覆盖。

试试这组代码来显示 TimePickerDialog。

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