如何在Xamarin Forms中按下按钮时关闭键盘 [英] How to dismiss keyboard on button press in Xamarin Forms

查看:505
本文介绍了如何在Xamarin Forms中按下按钮时关闭键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过大量的探索,对于iOS案例,我想出了一种方法来隐藏Xamarin Forms中按钮按下时的键盘.所以在下面分享.

After much hunting I worked out a way to hide the keyboard on a button press in Xamarin Forms, for the iOS case. So it's shared below.

如果任何人都可以改进它,或者共享Android方面的解决方案,那就太好了.

If anyone can improve it, or share a solution for the Android side, that would be great.

推荐答案

我发现这很有用:

https://forums.xamarin.com/discussion/comment/172077#Comment_172077

接口:

public interface IKeyboardHelper
{
    void HideKeyboard();
}

iOS:

public class iOSKeyboardHelper : IKeyboardHelper
{
    public void HideKeyboard()
    {
        UIApplication.SharedApplication.KeyWindow.EndEditing(true);
    }
}

机器人:

public class DroidKeyboardHelper : IKeyboardHelper
{
    public void HideKeyboard()
    {
        var context = Forms.Context;
        var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;
        if (inputMethodManager != null && context is Activity)
        {
            var activity = context as Activity;
            var token = activity.CurrentFocus?.WindowToken;
            inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);

            activity.Window.DecorView.ClearFocus();
        }
    }
}

以Xamarin形式使用:

DependencyService.Get<IKeyboardHelper>().HideKeyboard();

这篇关于如何在Xamarin Forms中按下按钮时关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆