在WebView中显示数字键盘

时间:2015-01-13 22:33:41

标签: android android-webview android-softkeyboard

我有一个webview,我在登录屏幕上手动显示键盘并专注于输入字段。

字段:

<input type="password" maxlength="4" pattern="[0-9]*" id="pin">

聚焦和显示键盘:

webView.requestFocus(View.FOCUS_DOWN);
webView.loadUrl("javascript:document.getElementById('pin').focus();");
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(webView, InputMethodManager.SHOW_IMPLICIT);

登录屏幕仅包含PIN样式代码字段,用户将在其中输入4位数字。问题是,默认情况下,它显示常规的alpha键盘,我希望它显示数字键盘。我已经看过许多使用EditText属性来控制键盘类型的例子。

InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
EditText.setInputType(InputType.TYPE_CLASS_PHONE); [select Input type as according to ur requirement]
mgr.showSoftInput(EditText, InputMethodManager.SHOW_IMPLICIT);

但是可以告诉键盘本身在WebView上显示什么类型或设置属性吗?

2 个答案:

答案 0 :(得分:5)

这条路线对我有用。创建WebView的子类,并覆盖方法onCreateInputConnection。当选择WebView中的输入字段时,将调用此方法,并且您可以自定义事件的处理方式。这是一个例子:

@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
    BaseInputConnection ic = new BaseInputConnection(this, true);
    outAttrs.inputType = InputType.TYPE_CLASS_NUMBER; // Tells the keyboard to show the number pad
    return ic;
}

答案 1 :(得分:1)

使用另一个答案建议的代码,在我的设备(Galaxy S4)和模拟器中正常工作。但是,当在另一台HTC设备上运行应用程序时,数字键不起作用。

将代码更改为以下内容:

@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
    InputConnection ic = super.onCreateInputConnection(outAttrs);
    outAttrs.inputType = InputType.TYPE_CLASS_NUMBER;
    return ic;
}

在我拥有的所有设备上工作。

相关问题