Share via

HOW TO GENERATE A TAPPED EVENT PROGRAMMATICALLY

Giorgio Sfiligoi 656 Reputation points
2024-10-27T08:29:15.8033333+00:00

Is it possible to "send" programmatically a Tapped event to a ContentPage?

i.e. simulate that the user tapped somewhere.

the platform is Android.

In my ContentPage I set HideSoftInputOnTapped="True"

There is an Entry:

        <Entry x:Name="entryField"
               ...
               IsReadOnly="True">
            <Entry.GestureRecognizers>
                <TapGestureRecognizer Tapped="OnFieldTapped" />
            </Entry.GestureRecognizers>
        </Entry>

It is read-only to prevent that tapping on it opens the soft keyboard.

Scenario:

  1. another field has its soft keyboard open;
  2. tapping anywhere will close it - this is the behavior that I want, BUT:
  3. tapping on the Entry above, the event is captured in my GestureRecognizer and does not close the existing soft keyboard.

The solution I envisage is: in my OnFieldTapped I forward the tapped event to the ContentPage or to any other element, to let the system close the software keyboard.

Developer technologies | .NET | .NET Multi-platform App UI

Answer accepted by question author

Anonymous
2024-10-29T04:00:30.9533333+00:00

in my OnFieldTapped I forward the tapped event to the ContentPage or to any other element, to let the system close the software keyboard.

For android, you can use inputMethodManager, then hide keyboard by inputMethodManager.HideSoftInputFromWindow method.

Please create a follow static class in the MainActivity.cs file or create a new class file in the Platform/Android folder.

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Views.InputMethods;


public static partial class KeyboardHelper
    {
        public static void HideKeyboard()
        {
            var context = Platform.AppContext;
            var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;
            if (inputMethodManager != null)
            {
                var activity = Platform.CurrentActivity;
                var token = activity.CurrentFocus?.WindowToken;
                inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);
                activity.Window.DecorView.ClearFocus();
            }
        }
    }

Then you can hide keyboard in the layout background code like following code.

#if ANDROID
            KeyboardHelper.HideKeyboard();
#endif

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.