【问题标题】:How to hide soft keyboard without cordova's plugins and without lost focus如何在没有cordova插件且不丢失焦点的情况下隐藏软键盘
【发布时间】:2023-03-22 20:33:01
【问题描述】:

当我点击没有插件的<input type=text> 并且没有失去input 的焦点时,我想隐藏Android 原生键盘。

使用 JavaScript,我可以检测键盘何时显示或隐藏,但我想在需要时隐藏。

backbutton在显示时隐藏了键盘,所以,我认为我可以在检测到showkeyboard事件时触发后退按钮单击事件,但它不起作用。

document.addEventListener("showkeyboard", 
    function(){ 
        alert("Keyboard is ON"); 
        $("backbutton").trigger('click'); // Doesn't work effect
    }, false);

document.addEventListener("hidekeyboard", 
    function(){ 
        alert("Keyboard is OFF");

    }, false);

【问题讨论】:

标签: javascript android jquery cordova dom-events


【解决方案1】:

首先在你的 mainactivity 导入中:

    import android.view.inputmethod.InputMethodManager;
    import android.webkit.JavascriptInterface;

然后在onCreate方法中添加一个javascript接口:

   super.appView.addJavascriptInterface(new JSInterface(), "testInterface");

然后在 Mainactivity 类中添加以下代码:

    @JavascriptInterface
    public void hideKeyboard() {
        runOnUiThread(new Runnable() {

            public void run() {
                try {
                    InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext().getSystemService(Service.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(<MainactivityClass>.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

现在从 HTML 中,像这样在输入框中调用原生 hideKeyboard() 方法:

    <input type="text" onfocus="window.testInterface.hideKeyboard()" />

【讨论】:

    【解决方案2】:

    直接使用试试

    document.getElementById('input_field_to_focus').focus();
    

    这会将焦点添加到输入字段,但不会调用软键盘。 Android 上不会触发键盘打开事件,除非它来自点击事件。

    参考链接:http://code.google.com/p/android/issues/detail?id=27438

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 1970-01-01
      • 2022-11-22
      • 2015-08-10
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多