[英]How can I show the soft keyboard in a webview with a USB HID device attached when a button is clicked and an input is focused?
我有一个USB条码扫描器,它通过USB OTG插入设备。 因为它被选为键盘HID设备,所以当输入被聚焦时,软键盘被禁用。
我目前有一个从JavaScript触发键盘的方法。
class JsObject {
@JavascriptInterface
public void InvokeKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(findViewById(R.id.webView), InputMethodManager.SHOW_FORCED);
}
}
webview.addJavascriptInterface(new JsObject(), "Android");
我基本上想要它在webview中的以下动作上打开键盘。
const button = document.querySelector('.fire-keyboard');
button.addEventListener('click', () => Android.InvokeKeyboard());
它可以在从webview手动调用时工作,但我希望能够单击触发它的按钮,然后单击按钮会丢失输入框焦点。
只是添加,我不希望键盘在聚焦输入框时显示,只显示单击按钮时触发它。 默认情况下,它显示焦点。
可能是因为您使用的设备。 我根据你的场景制作了一个样本,并在我正在使用的Nexus5
设备上成功运行它。
只需使用document.getElementById("mytextfield").focus();
在JS代码中完成了这个伎俩。
示例HTML代码
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="myform">
<input type="text" id="mytextfield">
</form>
<input type="button" value="Click Me!" onClick="executeAndroidCode()" />
<script type="text/javascript">
function executeAndroidCode() {
Android.execAndroid();
document.getElementById("mytextfield").focus(); //this line did the trick after click on button
}
</script>
</body>
</html>
将此文件保存在名为index.html
资产中
JavaScriptInterface
public class WebAppInterface
{
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void execAndroid() {
InputMethodManager inputMethodManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(findViewById(R.id.webView1),
InputMethodManager.SHOW_FORCED);
}
}
onCreate Code
WebView wv = (WebView) findViewById(R.id.webView1);
wv.addJavascriptInterface(new WebAppInterface(this), "Android");
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
wv.loadUrl("file:///android_asset/index.html");
它的工作正常我在使用Nexus5
。 虽然光标不会显示在屏幕截图中,但是当我运行应用程序时它会闪烁。
我现在无法测试它,但你可以简单地使用javascript接口来调用它:
InputMethodManager imeManager = (InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE);
imeManager.showInputMethodPicker();
这应该打开当前键盘(输入设备)的对话框。 由于蓝牙扫描仪取代了当前的键盘,我不确定您是否可以显示软键盘。
使用相同的方法,用户将根据需要切换回扫描仪。
我会在我回家的时候尝试它,从现在开始的6或7小时但是可以自由尝试自己;)
Try this
inputBox.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.