Search code examples
maui

MAUI Unable to fire Picker.focus() in Android programatically


Simple repro , create a new proj.

Add a Picker in Xaml

<Picker x:Name="myPicker">
     <Picker.Items>
         <x:String>Option 1</x:String>
         <x:String>Option 2</x:String>
         <x:String>Option 3</x:String>
     </Picker.Items>
</Picker>
<Button Text="Focus Picker" 
        Clicked="OnButtonClicked"/>

Add a Button and add a tapped event to that button

Code-behind

private void OnButtonClicked(object sender, EventArgs e)
{
    myPicker.Focus();
}

This works in iOS , but not in Android in MAUI. This worked in Xamarin, Any workaround to trigger this programmatically in MAUI?


Solution

  • This is a known issue on the GitHub. You can check this link about Fix (or don't) the behavior of calling "Focus" on Android to open the picker

    Here is workaround you can use for all platforms.

    private void OnButtonClicked(object sender, EventArgs e)
    {
        myPicker.Unfocus();
        myPicker.Focus();
    }
    

    Here is the Android platform solution.

    private void Button_Clicked(object sender, EventArgs e)
      {
        #if ANDROID
                    var nativePicker = myPicker.Handler.PlatformView as MauiPicker;
                    nativePicker.PerformClick();
        #endif
        
                }