Xamarin Android:在片段上隐藏键盘

时间:2018-03-09 10:48:46

标签: c# android xamarin.android

我在viewpager上有两个片段。由于一个片段上有EditTexts而另一个片段上只有图形,我想在切换到图形片段时隐藏键盘。

2 个答案:

答案 0 :(得分:2)

ViewPager.IOnPageChangeListener(包含xxxxActivity)中实施ViewPager。并使用addOnPageChangeListener(API级别24.1.0中已弃用setOnPageChangeListener。)在ViewPager添加侦听器。

OnPageSelected方法中:

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();方法:

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

答案 1 :(得分:0)

您可以在Xamarin.Android项目中的某种Utils类中使用静态方法。可能看起来像这样:

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);
        }
    }
}

查看GetSystemService(java.lang.String)InputMethodManager课程。