[英]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.