Search code examples
androidxamarin.formsandroid-softkeyboardandroid-keypadandroid-input-method

Xamarin Forms custom Entry renderer that hides soft keyboard


In a Xamarin Forms app, I am trying to create a custom Entry implementation that does not automatically display the soft keyboard when it is focused. The goal is to use one instance of this entry alongside other conventional entries on a page.

I am familiar with the recommended Xamarin Forms pattern for custom view rendering, and have successfully created both the Entry and its renderer, as follows:

public class BlindEntry : Entry
{
}

[assembly: ExportRenderer(typeof(BlindEntry), typeof(BlindEntryRenderer))]

public class BlindEntryRenderer : EntryRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.FocusChange += Control_FocusChange;
        }
    }

    private void Control_FocusChange(object sender, FocusChangeEventArgs e)
    {
        if (e.HasFocus)
        {
            // What goes here?
        }
        else
        {
            // What goes here?
        }
    }
}

To show and hide the soft keyboard, I imagine one of the recommendations from this question will provide the solution, but there are many different opinions on which is the best approach. Also, even after choosing a suitable pattern, I am not clear how to access the required native Android APIs from within the above custom renderer.

For example, I know that I can obtain a reference to an InputMethodManager using the following call (from within an Activity), but it is not obvious how to reference the containing activity from inside the renderer:

var imm = GetSystemService(InputMethodService)

Thanks, in advance, for your suggestions.

Tim


Solution

  • Try this instead inside OnElementChanged():

    Control.InputType = Android.Text.InputTypes.Null;
    

    This will prevent the keyboard from appearing when selecting the Entry without having to check its focus.

    === Edit ===

    Turns out there is actually the ShowSoftInputOnFocus property available for doing exactly this.

    Control.ShowSoftInputOnFocus = false;