在MvxFragment中关闭/隐藏安卓软键盘

8

我使用xamarin + mvvmcross创建Android应用程序。我在MvxFragment中有一个MvxAutoCompleteTextView。在MvxAutoCompleteTextView中输入内容并单击其他控件后,我想隐藏虚拟键盘。我使用以下代码:

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

但这并不起作用。我该如何隐藏键盘?
5个回答

7

您可以将焦点放在不是“键盘启动器”控件的内容上,例如,您自动完成控件的父容器,以隐藏软键盘。

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

假设您的父容器是LinearLayout,您应该使用以下两个属性允许其获得焦点:

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

6

我从这里得到了Java的答案:https://dev59.com/7m445IYBdhLWcg3wfKcZ#28939113

以下是C#版本(已测试并可用):

public override bool DispatchTouchEvent(MotionEvent ev)
{
    if (ev.Action == MotionEventActions.Down)
    {
        View v = CurrentFocus;
        if (v.GetType() == typeof(EditText))
        {
            Rect outRect = new Rect();
            v.GetGlobalVisibleRect(outRect);
            if (!outRect.Contains((int)ev.RawX, (int)ev.RawY))
            {
                v.ClearFocus();
                InputMethodManager imm = (InputMethodManager)this.GetSystemService(Context.InputMethodService);
                imm.HideSoftInputFromWindow(v.WindowToken, 0);
            }
        }
    }
    return base.DispatchTouchEvent(ev);
}

如果您单击非EditText元素,此代码将隐藏软键盘。 您只需将其粘贴到活动类中(例如,您的loginActivity)即可。


3
尝试以下操作:

InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(autoComplete.WindowToken, 0);

HideSoftInputFromWindow中,值为0是常量Android.Views.InputMethods.HideSoftInputFlags.None,因此您可以使用等效的语法:

InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(autoComplete.WindowToken, Android.Views.InputMethods.HideSoftInputFlags.None);

2

试试我的函数:

public static void Close_AndroidKeyboard(Activity context){
    InputMethodManager inputManager = (InputMethodManager) context.getSystemService(
            Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);
}

抱歉,但我使用的是Android Studio,如果我有所帮助,祝您编程愉快!


0
我发现最简单的解决方案是,在具有焦点的控件上(例如一个 EntryEditor),直接调用 Unfocus() 方法。如果您想要直接在 XAML 中指定该函数,可以将此调用嵌入到 UnfocusOnClicked 行为中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接