Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 753
ratnamanjari swain Avatar asked May 27 '16 07:05

ratnamanjari swain


3 Answers

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

like image 82
Madhav Shenoy Avatar answered Oct 26 '22 17:10

Madhav Shenoy


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();
        }
    }
}
like image 20
Yksh Avatar answered Oct 26 '22 17:10

Yksh


 <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

like image 1
Ruchira Avatar answered Oct 26 '22 16:10

Ruchira