0

I am working on a concept which has a OTP screen. The requirement is to dismiss the keyboard automatically upon entering the last digit of the 6 digit OTP number.

Here is what I have done till now -

if (lastOTPEntry.Value != string.Empty)
{
    lastOTPEntry.Unfocus();
}

Then I have an EntryRenderer which overrides this method -

protected override void OnFocusChangeRequested(object sender, VisualElement.FocusRequestArgs e). 
{ 
   if (Control != null). 
   {    
        if (e.Focus)
        {
             Control.RequestFocus();
        }
        else
        {
            Control.ClearFocus();
        }
    }
}

Control is a FormsEditText But somehow the keyboard does not dismiss. What am I doing wrong here .. ?

Shailesh
  • 3,072
  • 3
  • 24
  • 33

1 Answers1

0

I needed to do something similar in older project and ended up using a service pattern to implement.

Android Service:

public class KeyboardService : IKeyboardService
{        
    public void HideKeyboard()
    {
        var context = Application.Context;
        var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;

        if (inputMethodManager != null && context is Activity)
        {
            var activity = context as Activity;
            var token = activity.CurrentFocus?.WindowToken;

            inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);
            activity.Window.DecorView.ClearFocus();
        }
    }
}

iOS Service:

public class KeyboardService : IKeyboardService
{
    public void HideKeyboard()
    {
        UIApplication.SharedApplication.KeyWindow.EndEditing(true);
    }
}

Interface:

public interface IKeyboardService
{
    void HideKeyboard();
}

To use, you'll need to register it with your dependency service the resolve it. After it's resolved, to use it:

if (lastOTPEntry.Value != string.Empty)
{
    keyboardService.HideKeyboard();
}

I haven't touched that project in a while but the logic should still work.

Andrew
  • 1,390
  • 10
  • 21
  • This works ! But what could be possibly wrong in the code that I have mentioned in the question..? – Shailesh Aug 05 '20 at 18:02
  • Not sure. Some quick looking around the internet seems to show that you can't just clear focus, you have to give something else focus. – Andrew Aug 05 '20 at 19:48
  • I too did some searching and ended up adding ‘base.onFocusChangeRequested’ and removing ‘control.clearfocus’ and it started to work. Any idea how ? What changed by calling the parent method ..? – Shailesh Aug 05 '20 at 19:53