DevNoteHQ
DevNoteHQ

Reputation: 303

Xamarin Android: Hide Keyboard on Fragment

I have two fragments on a viewpager. Since one fragment has EditTexts on it and the other has just graphics on it, I would like to hide the keyboard when I switch onto the graphic fragment.

Upvotes: 0

Views: 1556

Answers (2)

Robbit
Robbit

Reputation: 4358

Implement ViewPager.IOnPageChangeListener in your xxxxActivity( which contains the ViewPager). And use addOnPageChangeListener( setOnPageChangeListener was deprecated in API level 24.1.0.) to add listener on your ViewPager.

In the OnPageSelected method:

public void OnPageSelected(int position)
{

    if (position == 0)
    {
        // because the keyboard has been forced to hide in graphic fragment,
        // when you back to edittext fragment, you need force to show it.
        EditTextFragment.showKeyboard();
    }
    else if (position == 1)
    {
        //In your graphic fragment, hide the keyboard.
            var im = ((InputMethodManager)GetSystemService(Android.Content.Context.InputMethodService));

            if (CurrentFocus!= null)
            {
                im.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
            }
    }
}

EditTextFragment.showKeyboard(); method:

    if (editText.RequestFocus())
    {
        InputMethodManager imm = (InputMethodManager)Activity.GetSystemService(Android.Content.Context.InputMethodService);
        imm.ShowSoftInput(editText,ShowFlags.Implicit );
    }

Upvotes: 3

Raimo
Raimo

Reputation: 1534

You could use a static method for this in a sort of Utils class inside your Xamarin.Android project. Might look kind of like this:

public static class Utils
{
    public static void HideKeyboard(Activity context)
    {
        var imm = (InputMethodManager)context.GetSystemService(Context.InputMethodService);
        int sdk = (int)Build.VERSION.SdkInt;

        if (sdk < 11)
        {
            imm.HideSoftInputFromWindow(context.Window.CurrentFocus.WindowToken, 0);
        }
        else
        {
           imm.HideSoftInputFromWindow(context.CurrentFocus.WindowToken, HideSoftInputFlags.NotAlways);
        }
    }
}

Take a look at GetSystemService(java.lang.String) and the InputMethodManager class.

Upvotes: 0

Related Questions