How to use #getSystemService in Maui?

1k Views Asked by At

I'm implementing a Maui app, and got stuck with the bug whereby the soft keyboard is not displayed when an Entry control gains focus. The entry control is focused, the cursor blinks, the keyboard remains hidden.
(For the other way around, hiding the keyboard, I am aware of the disable/enable hack.)
I tried many things, the next one is using platform interop to force-show it.
I found some suggestion to use Context.getSystemService(Context.InputMethodManager) as InputMethodManager, but getSystemService is not avaialable on the Android.Content.Context object provided by Maui.

So to get me started, can someone help with an example on how to use getSystemService from Maui to get a reference to an InputMethodManager?

XAML

<ContentPage.Content>
<ScrollView>
    <StackLayout x:Name="MainLayout"
        Padding="30,100">
        <Label Text="Password" />
        <Frame CornerRadius="15" Padding="0">
            <Entry x:Name="PinEntry" 
                Text="{Binding Pin}"
                FontSize="20"
                HorizontalTextAlignment="Center"
                Loaded="PinEntry_Loaded"
                Keyboard="Telephone"/>
        </Frame>
        <Button x:Name="LoginButton"
            Text="Log in"
            FontSize="20"
            Clicked="LoginButton_Clicked"
            Padding="12"
            Margin="0,30" />
    </StackLayout>
</ScrollView>
</ContentPage.Content>

Codebehind

private async void PinEntry_Loaded(object sender, EventArgs e)
{
    PinEntry.Focus();
}

Also tried

private async void PinEntry_Loaded(object sender, EventArgs e)
{
    PinEntry.Focus();
    var _ = SoftKeyboardHelper.Show();
}

where SoftkeyboardHelper complete implementation is:

#if ANDROID
using Android.Content;
using Android.Views;
using Android.Views.InputMethods;
using Android.Runtime;
using Android.OS;
#endif

namespace Waiter.Maui.Platforms.Android
{
    public partial class SoftKeyboardHelper
    {
        public static async Task Show()
        {
#if ANDROID
            await Task.Run(async () =>
            {
                await Task.Delay(5000);
                var imm = (InputMethodManager)MauiApplication.Current
                    .GetSystemService(Context.InputMethodService);
                if (imm != null)
                {
                    var activity = Microsoft.Maui.ApplicationModel
                        .Platform.CurrentActivity;
                    IBinder wToken = activity.CurrentFocus?.WindowToken;
                    imm.ShowSoftInputFromInputMethod(wToken, 0);
                }
            });
#else
            // Do nothing on other platforms
#endif
        }
    }
}
0

There are 0 best solutions below