Xamarin Forms Android DatePicker仅显示Spinner,日历仍弹出求助
Fix: Xamarin.Forms DatePicker Only Show Spinner on API 22
Hey there, let's figure out how to get your DatePicker to only display the spinner selector (and hide the calendar pop-up) on API 22 in Xamarin.Forms! Since most existing solutions target API 24+, we'll need a custom Android renderer specifically tailored for this older Android version.
Step 1: Create a Custom DatePicker in Your Shared Project
First, we'll define a custom DatePicker control in your shared code—this lets us target it with our Android renderer later:
using Xamarin.Forms; namespace YourAppNamespace { // Just a wrapper around the default DatePicker to apply our custom rendering public class SpinnerOnlyDatePicker : DatePicker { } }
Step 2: Implement the Android Custom Renderer
In your Android project, add a renderer that modifies the native DatePickerDialog to hide the calendar view and force spinner mode:
using Android.App; using Android.Content; using Android.Widget; using YourAppNamespace; using YourAppNamespace.Droid; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(SpinnerOnlyDatePicker), typeof(SpinnerOnlyDatePickerRenderer))] namespace YourAppNamespace.Droid { public class SpinnerOnlyDatePickerRenderer : DatePickerRenderer { public SpinnerOnlyDatePickerRenderer(Context context) : base(context) { } protected override DatePickerDialog CreateDatePickerDialog(int year, int month, int day) { var dialog = base.CreateDatePickerDialog(year, month, day); // Get the native DatePicker component from the dialog var nativeDatePicker = dialog.FindViewById<DatePicker>(Resource.Id.datePicker); if (nativeDatePicker != null) { // Hide the calendar view and show only the spinners nativeDatePicker.CalendarViewShown = false; nativeDatePicker.SpinnersShown = true; } return dialog; } } }
Step 3: Use the Custom Control in Your XAML
Replace your existing DatePicker with our new SpinnerOnlyDatePicker in your XAML files:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:YourAppNamespace" x:Class="YourAppNamespace.MainPage"> <StackLayout Padding="20"> <!-- Use our custom spinner-only date picker --> <local:SpinnerOnlyDatePicker Title="Select Date" Format="MM/dd/yyyy" /> </StackLayout> </ContentPage>
Key Notes
- For API 22, the native Android
DatePickerhas direct properties (CalendarViewShownandSpinnersShown) to toggle which parts are displayed—this is why this approach works where API 24+ solutions (which useDatePickerDialog.ToggleCalendarView()) don't. - Make sure your Android project's target framework includes API 22 (you can check this in your project properties under Android Options).
- If you still see the calendar, double-check that you're using the custom
SpinnerOnlyDatePickerinstead of the default Xamarin.FormsDatePickerin all places.
内容的提问来源于stack exchange,提问作者tlauer




