在WebView中显示数字键盘

6

我有一个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 码输入框。问题在于默认情况下,它显示的是常规的字母键盘,而我希望它显示数字键盘。我看过很多使用 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上设置属性呢?

你找到解决方案了吗? - Mohamed Khamis
2个回答

6
这个方法对我有用。创建一个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

使用另一个答案建议的代码在我的设备(Galaxy S4)和模拟器上运行良好。然而,在另一台HTC设备上运行应用程序时,数字键无法正常工作。

将代码更改为以下内容:

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

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


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