Close/hide the Android Soft Keyboard in MvxFragment

FetFrumos picture FetFrumos · Jun 18, 2015 · Viewed 8.2k times · Source

I create android app with xamarin + mvvmcross. I have an MvxAutoCompleteTextView in my MvxFragment. After writing in the MvxAutoCompleteTextView and clicking on the others controls, I want to hide the virtual keyboard. I use this code

public class MyFragment : MvxFragment 
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState)
    {

        base.OnCreateView(inflater, container, savedInstanceState);
        var view = this.BindingInflate(Resource.Layout.frMy, null);
        var autoComplete = view.FindViewById<MvxAutoCompleteTextView>(Resource.Id.acMy);
        InputMethodManager inputManager = (InputMethodManager)inflater.Context.GetSystemService(Context.InputMethodService);
        inputManager.HideSoftInputFromWindow(autoComplete.WindowToken, HideSoftInputFlags.None);
        return view;
    }
}

but this not work. How do I hide the keyboard?

Answer

xleon picture xleon · Jun 19, 2015

You can hide the soft keyboard giving focus to something that is not a "keyboard launcher" control, for example, the parent container of your auto-complete control.

parentContainer = FindViewById<LinearLayout>(Resource.Id.parentContainer);
parentContainer.RequestFocus();

Let´s say your parent container is a LinearLayout, you should allow it to get focus with these 2 properties:

<LinearLayout
    android:id="@+id/parentContainer"
    android:focusable="true"
    android:focusableInTouchMode="true">