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

ratnamanjari swain picture ratnamanjari swain · May 27, 2016 · Viewed 19.1k times · Source

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

Answer

Yksh picture Yksh · May 27, 2016

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