我想在Android网页浏览中输入特殊字符(例如'ä','é','£'等)。 这些字符不包含在虚拟KCM(关键字符映射)中。所以我无法检索与该角色关联的键码并创建一个KeyEvent。
我尝试了不同的方法:
String t = "testàaâäù";
char[] charArray = t.toCharArray();
if (charArray.length > 0) {
KeyCharacterMap keyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
KeyEvent[] events = keyCharacterMap.getEvents(charArray);
}
// events is null, because some characters aren't include in KCM
// it never works in any case
使用仪器方法:
instrumentation.sendStringSync("a"); // Display 'a'
instrumentation.sendStringSync("àâä"); // Display nothing
instrumentation.sendCharacterSync(KeyEvent.KEYCODE_H); // Display 'h'
// Instrumentation seems to use KCM for data entry
使用ACTION_MULTIPLE KeyEvent:
KeyEvent event = new KeyEvent(SystemClock.uptimeMillis(), String.valueOf("aàâä"), 0, 0);
focusedView.dispatchKeyEvent(event);
// Doesn't work with WebView, but works with other components such as EditText.
// I get this error: Unimplemented WebView method onKeyMultiple called from: android.webkit.WebView.onKeyMultiple
我可以实现onKeyMultiple(WebView)方法来处理数据输入吗?是否有在webview中输入特殊字符的解决方案?我需要一个不需要root或创建键盘布局的解决方案(用户不必选择键盘)。
答案 0 :(得分:1)
在WebView内的输入字段上使用虚拟键盘编写时遇到了同样的问题。它不会识别像“á”这样的特殊字符。我做了什么:
if (event.getAction() == KeyEvent.ACTION_MULTIPLE) {
loadUrl("javascript:var prevText = document.activeElement.value;" +
"var afterText = document.activeElement.value = prevText + \"" + event.getCharacters() + "\";");
return false;
}
当使用Javascript操作ACTION_MULTIPLE时,我得到输入字段,并附加特殊字符。
以下是全班:
public class CustomWebView extends WebView {
public CustomWebView (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
ExtenderInputConnection connection = new ExtenderInputConnection(this, false);
outAttrs.imeOptions = EditorInfo.IME_ACTION_SEARCH;
return connection;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_MULTIPLE) {
loadUrl("javascript:var prevText = document.activeElement.value;" +
"var afterText = document.activeElement.value = prevText + \"" + event.getCharacters() + "\";");
return false;
}
return super.dispatchKeyEvent(event);
}
public class ExtenderInputConnection extends BaseInputConnection implements InputConnection {
public ExtenderInputConnection(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
}
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
if (beforeLength == 1 && afterLength == 0) {
// backspace
return super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) && super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
}
return super.deleteSurroundingText(beforeLength, afterLength);
}
}
}
希望它有所帮助。