简体   繁体   中英

Show numeric keyboard in a WebView

I have a webview where I am manually showing the keyboard on the login screen and focusing on the input field.

Field:

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

Focus and show keyboard:

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

The login screen consists of only a PIN style code field where the user will enter 4 digits. The problem is that by default it shows the regular alpha keyboard and I want it to show the numeric keyboard instead. I've seen lots of examples of using an EditText's properties to control the type of keyboard eg

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

But is it possible to tell the keyboard itself what type to show or set the attribute on the WebView?

This route worked for me. Create a subclass of WebView , and override the method onCreateInputConnection . This method gets called when an input field in the WebView is selected, and it gives you an opportunity to customize how the event is handled. Here's an example:

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

Using the code the another answer suggests, works fine in my device (Galaxy S4) and the emulator. However when running the app in another HTC device the number keys does not work.

Change the code to the following:

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

worked on all devices I have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM