Datepicker:如何使用C#xamarin单击edittext时弹出datepicker

时间:2016-05-27 07:53:17

标签: c# xamarin xamarin.android android-datepicker

如何在Xamarin.Android中的编辑文本点击或焦点事件中显示日期选择器弹出窗口?

4 个答案:

答案 0 :(得分:11)

为Xamarin.Forms尝试类似的东西:

public class SamplePage : ContentPage
{
    public SamplePage ()
    {
        var editText = new Entry {
            Placeholder = "Select Date.",
        };

        var date = new DatePicker {
            IsVisible = false,
            IsEnabled = false,
        };

        var stack = new StackLayout {
            Orientation = StackOrientation.Vertical,
            Children = {editText, date}
        };

        editText.Focused += (sender, e) => {
            date.Focus();
        };
        date.DateSelected += (sender, e) => {
            editText.Text = date.Date.ToString();
        };

        Content = stack;
    }
}

编辑:

为Xamarin.Android尝试类似的事情:

<强> MyLayout.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText" />
</LinearLayout>

<强> MyLayoutActivity.cs

using System;
using Android.App;
using Android.OS;
using Android.Widget;

namespace AndiNative
{
    [Activity (Label = "MyLayoutActivity", MainLauncher = true)]            
    public class MyLayoutActivity: Activity
    {
        private static EditText editText;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.DatePickerTest);

            editText = FindViewById<EditText> (Resource.Id.editText);

            editText.Click += (sender, e) => {
                DateTime today = DateTime.Today;
                DatePickerDialog dialog = new DatePickerDialog(this, OnDateSet, today.Year, today.Month - 1, today.Day);
                dialog.DatePicker.MinDate = today.Millisecond;
                dialog.Show();
            };
        }

        void OnDateSet(object sender, DatePickerDialog.DateSetEventArgs e)
        {
            editText.Text = e.Date.ToLongDateString();
        }
    }
}

答案 1 :(得分:3)

对于那些喜欢MVVM的人。这是Xamarin Forms中的MVVM实现。我在这里使用了Event to Command行为。您可以通过此链接获得更多信息 Xamarin Event to Command Behaviors

<强>的Xaml

    <Entry Text="{Binding DateOfBirth, Mode=TwoWay}" />
    <Image Source="button.png" WidthRequest="39">
        <Image.GestureRecognizers>
            <TapGestureRecognizer Command="{Binding OnSelectDOBCommand}" CommandParameter="{Binding ., Source={Reference DOBPicker}}" />
        </Image.GestureRecognizers>
    </Image>
    <DatePicker x:Name="DOBPicker"
                Date="{Binding SelectedDOB}"
                IsEnabled="True"
                IsVisible="False">
        <DatePicker.Behaviors>
            <behaviors:DatePickerSelectedBehavior Command="{Binding DateSelectedCommand}" EventName="DateSelected" />
        </DatePicker.Behaviors>
    </DatePicker>

查看型号代码

OnSelectDOBCommand = new RelayCommand<DatePicker>(FocusDatePicker);
DateSelectedCommand = new RelayCommand(SetDateOfBirth);

现在功能定义

    private void FocusDatePicker(DatePicker obj)
    {
        obj.Focus();
    }
    private void SetDateOfBirth()
    {
        DateOfBirth = SelectedDOB;
    }

希望这有助于某人

2016年11月11日更新

另一种选择是简单明了地使用ACR.Userdialogs。声明你的ICommand

 OnSelectDOBCommand = new RelayCommand(ShowDatePicker);

接下来定义ShowDatePicker函数

private void ShowDatePicker()
{            
   UserDialogs.Instance.DatePrompt(new DatePromptConfig { MaximumDate = MaxDate, OnAction = (result) => SetDateOfBirth(result), IsCancellable = true });
}

设定出生日期功能

private void SetDateOfBirth(DatePromptResult result)
    {            
        if(result.Ok)
        {
            DateOfBirth = result.SelectedDate.ToString("dd MMM yyyy");
        }

    }

最好的部分,你根本不需要任何特殊的Xaml。你可以将它挂钩到任何按钮。

艾伦应该获得奖励或其他什么

答案 2 :(得分:1)

 <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginBottom="15dp"
    android:id="@+id/datePickerText"
    android:textColor="@color/textColor"
    android:textColorHint="@color/textColor"
    android:textSize="14dp"
    local:MvxBind="Value Format('{0:dd MMM yyyy}',Date)" />
viewmodel中的

属性 -

    private DateTime _date = DateTime.Today;
    public DateTime Date
    {
        get
        {
            return _date;
        }
        set
        {
            _date = value;
            RaisePropertyChanged(() => Date);
        }
    }

在我的班级里面 -

      private EditText datePickerText;
      private DatePickerDialogFragment dialog;
      protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.report);

        var dp = new MvxDatePicker(this);
        dp.SpinnersShown = true;
        dp.DateTime = DateTime.Now;
        datePickerText.Focusable = false;
        datePickerText.Text = ViewModel.Date.ToString("dd-MMM-yyyy");

        datePickerText.Click += (sender, args) =>
        {
        if(datePickerText.Text == "")
  dialog = new DatePickerDialogFragment(this, DateTime.Now,this);
       else
  dialog = new   DatePickerDialogFragment(this,Convert.ToDateTime(datePickerText.Text), this);

  dialog.Show(this.SupportFragmentManager, "date");
        };

        datePickerText.TextChanged += (sender, args) =>
        {
            ViewModel.Date = Convert.ToDateTime(datePickerText.Text);
        };
    }

  public void OnDateSet(DatePicker view, int year, int monthOfYear, int   dayOfMonth)
    {
        datePickerText.Text = new DateTime(year, monthOfYear + 1, dayOfMonth).ToString("dd-MMM-yyyy");
    }
  

这里需要今天的默认日期,它会更改为用户选择的日期

答案 3 :(得分:0)

尽管我发现所有答案在不同程度上都有趣且有用,但并没有涵盖所有内容。这是针对普通Xamarin.Android的处理方法。

public class MyActivity : MyActivityBase
{
    private int _dateViewId { get; set; }
    private DateTime _myDate { get; set; }

    protected override void OnCreate (Bundle savedInstanceState)
    {
        base.OnCreate (savedInstanceState);
        SetContentView (Resource.Layout.activity_my);

        InitDateField ();
    }

    private void InitDateField ()
    {
        var rootLayout = FindViewById (Resource.Id.your_root_xaml_layout);
        rootLayout.AddView (GetNewDateView ());
    }

    private View GetNewDateView ()
    {
        var view = new EditText (this);
        view.InputType = InputTypes.DatetimeVariationDate;
        view.Hint = "Insert date";

        view.Id = View.GenerateViewId ();

        view.FocusChange += DateField_Click;
        view.Click += DateField_Click;

        return view;
    }

    private void DateField_Click (object sender, EventArgs e)
    {
        var view = (sender as EditText);

        if (view.IsFocused)
        {
            _dateViewId = view.Id;

            var date = DateTime.Today;

            // NB. The month needs translating here for the datepicker.
            var dialog = new DatePickerDialog (this, OnDateSet, date.Year, date.Month - 1, date.Day);
            dialog.Show ();
        }
    }

    private void OnDateSet (object sender, DatePickerDialog.DateSetEventArgs e)
    {
        // Store the date value for use in code.
        _myDate = e.Date;

        // Display the date in the desired format.
        var dateView = FindViewById<EditText> (_dateViewId);
        dateView.Text = e.Date.ToString ("dd/MM/yyyy");
    }
}

以两种方式之一触发日期选择器对话框:- 1.直接在日期字段上点击。 2.按键盘上的“下一步”,同时关注上一个字段,即可到达。

由于OnDateSet()方法不具有EditText.Id的先验知识,因此在触发准备在随后更新其值的日期选择器时存储ID。