Xamarin Forms – Android – Exception in DatePicker

How to reproduce it

Recently I came across with an interesting bug in Xamarin Forms.

The bug is in the DatePicker control. A DatePicker is, as the name states, a control to pick a specific date in the calendar. It’s displayed like this:

It renders in Android, first, like an Xamarin Forms Entry, and when you tap on it, it displayed the pop up with days/months/years.

The thing is that if you quickly double tap, the code doesn’t prevent the “double tap protection”. So, double tap gives you two popups, and when you close the first-opened popup, you get an unhandled exception and you app closed itself.

The bug is already reported here:

https://bugzilla.xamarin.com/show_bug.cgi?id=53656
And the culprit:

https://github.com/xamarin/Xamarin.Forms/blob/2.3.3/Xamarin.Forms.Platform.Android/Renderers/DatePickerRenderer.cs#L113

One solution

So a possible quick solution goes like this:


<StackLayout Grid.Column="1" Grid.Row="0"  HorizontalOptions="FillAndExpand" Padding="5, 0" VerticalOptions="Center">
        <StackLayout.GestureRecognizers>
                <TapGestureRecognizer NumberOfTapsRequired="1" Tapped="DateFromTapped"></TapGestureRecognizer>
        </StackLayout.GestureRecognizers>
        <Label Text="{Binding FormattedDateFrom}" VerticalOptions="End" HorizontalOptions="FillAndExpand" TextColor="Black">
                <Label.GestureRecognizers>
                        <TapGestureRecognizer NumberOfTapsRequired="1" Tapped="DateFromTapped"></TapGestureRecognizer>
                </Label.GestureRecognizers>
        </Label>
        <DatePicker Grid.Column="1" Grid.Row="0" Date="{Binding From}" x:Name="DateFrom" IsVisible="False"></DatePicker>
        <BoxView BackgroundColor="Black" HeightRequest="1" HorizontalOptions="FillAndExpand" VerticalOptions="End">
                <BoxView.GestureRecognizers>
                        <TapGestureRecognizer NumberOfTapsRequired="1" Tapped="DateFromTapped"></TapGestureRecognizer>
                </BoxView.GestureRecognizers>
        </BoxView>
</StackLayout>

What basically do is to create a hidden DatePicker, and handle the open/close of that DatePicker through a StackLayout and a Label.

That is really what a DatePicker is behind the scene: an Entry plus Labels plus a popup.

Hope that helps.

2018-09-20T19:43:57-03:00By |