Datepicker: How to popup datepicker when click on edittext using C# xamarin

20,101

Solution 1

Try something like this for 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;
    }
}


Edit :

Try something like this for 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();
        }
    }
}

Solution 2

For those of you who like MVVM. This is the MVVM implementation in Xamarin Forms. I've used Event to Command behavior here. You can get more on that from this link 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>

View Model Code

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

Now the function definitions

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

Hope this helps someone

Update 11/11/2016

The other alternative is to to use ACR.Userdialogs simple and straightforward. Declare your ICommand

 OnSelectDOBCommand = new RelayCommand(ShowDatePicker);

Next define the function ShowDatePicker

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

And the set date of birth function

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

    }

The best part, you dont need any special Xaml at all. You can hook it to any button.

Allan should be given an award or something

Solution 3

 <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)" />

property in viewmodel-

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

Inside my Class-

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

here it takes the default date for today orelse it changes to date selected by user

Share:
20,101
ratnamanjari swain
Author by

ratnamanjari swain

Updated on May 13, 2020

Comments

  • ratnamanjari swain
    ratnamanjari swain about 4 years

    How to show a date picker popup on Edit Text click or focus event in Xamarin.Android ?

  • ratnamanjari swain
    ratnamanjari swain about 8 years
    i have to create a class.. what about the click event code
  • Ruchira
    Ruchira about 7 years
    @ratnamanjariswain -Accept my answer if it helped you.You have asked the question for xamarin.android using MVVM so the solution will help you !!! Best regards.. :)
  • Shweta Nandha
    Shweta Nandha about 6 years
    getting Error: 'behaviors' is an undeclared prefix.
  • Madhav Shenoy
    Madhav Shenoy about 6 years
    Yes, that's probably because you're just copy pasting and haven't read through my post. You need to create a custom behavior. Open the link I've shared, it will tell you how to create an EventToCommand behavior.In this case, you need to create a custom behavior for the DatePicker
  • Rachel
    Rachel over 5 years
    How can i hook the UserDialogs.Instance.DatePrompt to a icon?
  • Madhav Shenoy
    Madhav Shenoy over 5 years
    I think with the new version of XForms they have provided a ImageButton. Previously I would use the TapGesture to hook up a function and then invoke UserDialogs.Instance.DatePrompt