我正在覆盖视图(openGL 表面视图)的 onKeyDown 方法来捕获所有按键。问题是在几个设备上 KEYCODE_DEL 没有被捕获。我尝试在视图中添加一个 onKeyListener ,并且捕获了除退格键之外的所有内容。
必须有一种方法来收听这个按键事件,但是怎么做呢?
2014 年 11 月 12 日更新:将修复范围更改为不限于 < API 级别 19,因为在第三方键盘上仍然存在超过 19 的错误。
2014 年 1 月 9 日更新:我设计了一种方法,使用代码来解决所有 Google 键盘 (LatinIME) KEYCODE_DEL 问题,特别是问题 42904 和 62306。
经许可,Turix 答案中的增强功能已被合并到我自己的代码中。Turix 的改进需要将垃圾字符注入可编辑缓冲区,而是找到一种增量方式来确保该缓冲区中始终只有一个字符。
我在部署的应用程序中使用了(类似的)代码,欢迎您测试:
https://play.google.com/store/apps/details?id=com.goalstate.WordGames.FullBoard.trialsuite]
介绍:
就这两个错误而言,下面介绍的解决方法适用于过去和未来的所有版本的 Google 键盘。此解决方法不要求应用程序保持针对 API 级别 15 或以下的卡住,某些应用程序已将自己限制在此范围内,以便利用绕过问题 42904 的兼容性代码。
这些问题仅作为已实现 onCreateInputConnection() 覆盖并将 TYPE_NULL 返回到调用 IME(在由 IME 传递给该方法的 EditorInfo 参数的 inputType 成员中)的视图的错误出现。只有通过这样做,视图才能合理地预期按键事件(包括 KEYCODE_DEL)将从软键盘返回给它。因此,此处介绍的解决方法需要 TYPE_NULL InputType。
对于不使用 TYPE_NULL 的应用程序,视图从其 onCreateInputConnection() 覆盖返回的 BaseInputConnection 派生对象中有各种覆盖,这些覆盖由 IME 在用户执行编辑时调用,而不是由 IME 生成键事件。这种(非 TYPE_NULL)方法通常更优越,因为软键盘的功能现在已经远远超出了单纯的按键敲击,还包括语音输入、完成等。按键事件是一种较旧的方法,谷歌实施 LatinIME 的人说他们希望看到 TYPE_NULL(和关键事件)的使用消失。
如果停止使用 TYPE_NULL 是一种选择,那么我会敦促您继续使用推荐的方法,使用 InputConnection 覆盖方法而不是键事件(或者更简单地说,使用从 EditText 派生的类,它会为您做到这一点)。
尽管如此,TYPE_NULL 行为并未正式停止,因此在某些情况下 LatinIME 无法生成 KEYCODE_DEL 事件确实是一个错误。我提供以下解决方法来解决此问题。
概述:
应用程序在从 LatinIME 接收 KEYCODE_DEL 时遇到的问题是由于两个已知的错误,如此处所述:
https://code.google.com/p/android/issues/detail?id=42904 (列为 WorkingAsIntended,但我认为问题是一个错误,因为它导致无法支持针对应用程序定位的 KEYCODE_DEL 事件生成API 级别 16 及更高版本已明确列出了 TYPE_NULL 的 InputType。该问题已在 LatinIME 的最新版本中修复,但过去的版本仍然存在此错误,因此使用 TYPE_NULL 并针对 API 级别 16 或以上仍然需要可以从应用程序内执行的解决方法。
在这里:
http://code.google.com/p/android/issues/detail?id=62306 (目前列为已修复但尚未发布 - FutureRelease - 但即使发布后,我们仍然需要可以执行的解决方法从应用程序内部处理将“在野外”持续存在的过去版本)。
与本文一致(KEYCODE_DEL 事件遇到的问题是由于 LatinIME 中的错误),我发现当使用外部硬件键盘时,以及使用第三方 SwiftKey 软键盘时,这些问题都不会发生,而他们对于特定版本的 LatinIME确实会发生。
这些问题中的一个或另一个(但不是同时出现)在某些 LatinIME 版本中存在。因此,开发人员在测试过程中很难知道他们是否解决了所有 KEYCODE_DEL 问题,并且有时当执行 Android(或 Google 键盘)更新时,问题将不再在测试中重现。尽管如此,导致问题的 LatinIME 版本将出现在相当多的正在使用的设备上。这迫使我深入研究 AOSP LatinIME git repo 以确定这两个问题中每一个的确切范围(即,可能存在这两个问题的特定 LatinIME 和 Android 版本)。下面的解决方法代码仅限于这些特定版本。
下面提供的解决方法代码包含大量注释,可以帮助您理解它试图完成的任务。在演示代码之后,我将提供一些额外的讨论,其中将包括特定的 Android 开源项目 (AOSP) 提交,其中引入了两个错误中的每一个,以及它消失的位置,以及可能的 Android 版本包括受影响的 Google 键盘版本。
我会警告任何想使用这种方法来执行他们自己的测试以验证它是否适用于他们的特定应用程序的人。我认为它通常可以工作,并且已经在许多设备和 LatinIME 版本上进行了测试,但是推理很复杂,所以要谨慎行事。如果您发现任何问题,请在下面发表评论。
代码:
那么,这里是我对这两个问题的解决方法,并在代码的注释中包含了解释:
首先,在您的应用程序中包含以下类(根据口味编辑),在其自己的源文件 InputConnectionAccomodatingLatinIMETypeNullIssues.java 中:
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
/**
*
* @author Carl Gunther
* There are bugs with the LatinIME keyboard's generation of KEYCODE_DEL events
* that this class addresses in various ways. These bugs appear when the app
* specifies TYPE_NULL, which is the only circumstance under which the app
* can reasonably expect to receive key events for KEYCODE_DEL.
*
* This class is intended for use by a view that overrides
* onCreateInputConnection() and specifies to the invoking IME that it wishes
* to use the TYPE_NULL InputType. This should cause key events to be returned
* to the view.
*
*/
public class InputConnectionAccomodatingLatinIMETypeNullIssues extends BaseInputConnection {
//This holds the Editable text buffer that the LatinIME mistakenly *thinks*
// that it is editing, even though the views that employ this class are
// completely driven by key events.
Editable myEditable = null;
//Basic constructor
public InputConnectionAccomodatingLatinIMETypeNullIssues(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
}
//This method is called by the IME whenever the view that returned an
// instance of this class to the IME from its onCreateInputConnection()
// gains focus.
@Override
public Editable getEditable() {
//Some versions of the Google Keyboard (LatinIME) were delivered with a
// bug that causes KEYCODE_DEL to no longer be generated once the number
// of KEYCODE_DEL taps equals the number of other characters that have
// been typed. This bug was reported here as issue 62306.
//
// As of this writing (1/7/2014), it is fixed in the AOSP code, but that
// fix has not yet been released. Even when it is released, there will
// be many devices having versions of the Google Keyboard that include the bug
// in the wild for the indefinite future. Therefore, a workaround is required.
//
//This is a workaround for that bug which just jams a single garbage character
// into the internal buffer that the keyboard THINKS it is editing even
// though we have specified TYPE_NULL which *should* cause LatinIME to
// generate key events regardless of what is in that buffer. We have other
// code that attempts to ensure as the user edites that there is always
// one character remaining.
//
// The problem arises because when this unseen buffer becomes empty, the IME
// thinks that there is nothing left to delete, and therefore stops
// generating KEYCODE_DEL events, even though the app may still be very
// interested in receiving them.
//
//So, for example, if the user taps in ABCDE and then positions the
// (app-based) cursor to the left of A and taps the backspace key three
// times without any evident effect on the letters (because the app's own
// UI code knows that there are no letters to the left of the
// app-implemented cursor), and then moves the cursor to the right of the
// E and hits backspace five times, then, after E and D have been deleted,
// no more KEYCODE_DEL events will be generated by the IME because the
// unseen buffer will have become empty from five letter key taps followed
// by five backspace key taps (as the IME is unaware of the app-based cursor
// movements performed by the user).
//
// In other words, if your app is processing KEYDOWN events itself, and
// maintaining its own cursor and so on, and not telling the IME anything
// about the user's cursor position, this buggy processing of the hidden
// buffer will stop KEYCODE_DEL events when your app actually needs them -
// in whatever Android releases incorporate this LatinIME bug.
//
// By creating this garbage characters in the Editable that is initially
// returned to the IME here, we make the IME think that it still has
// something to delete, which causes it to keep generating KEYCODE_DEL
// events in response to backspace key presses.
//
// A specific keyboard version that I tested this on which HAS this
// problem but does NOT have the "KEYCODE_DEL completely gone" (issue 42904)
// problem that is addressed by the deleteSurroundingText() override below
// (the two problems are not both present in a single version) is
// 2.0.19123.914326a, tested running on a Nexus7 2012 tablet.
// There may be other versions that have issue 62306.
//
// A specific keyboard version that I tested this on which does NOT have
// this problem but DOES have the "KEYCODE_DEL completely gone" (issue
// 42904) problem that is addressed by the deleteSurroundingText()
// override below is 1.0.1800.776638, tested running on the Nexus10
// tablet. There may be other versions that also have issue 42904.
//
// The bug that this addresses was first introduced as of AOSP commit tag
// 4.4_r0.9, and the next RELEASED Android version after that was
// android-4.4_r1, which is the first release of Android 4.4. So, 4.4 will
// be the first Android version that would have included, in the original
// RELEASED version, a Google Keyboard for which this bug was present.
//
// Note that this bug was introduced exactly at the point that the OTHER bug
// (the one that is addressed in deleteSurroundingText(), below) was first
// FIXED.
//
// Despite the fact that the above are the RELEASES associated with the bug,
// the fact is that any 4.x Android release could have been upgraded by the
// user to a later version of Google Keyboard than was present when the
// release was originally installed to the device. I have checked the
// www.archive.org snapshots of the Google Keyboard listing page on the Google
// Play store, and all released updates listed there (which go back to early
// June of 2013) required Android 4.0 and up, so we can be pretty sure that
// this bug is not present in any version earlier than 4.0 (ICS), which means
// that we can limit this fix to API level 14 and up. And once the LatinIME
// problem is fixed, we can limit the scope of this workaround to end as of
// the last release that included the problem, since we can assume that
// users will not upgrade Google Keyboard to an EARLIER version than was
// originally included in their Android release.
//
// The bug that this addresses was FIXED but NOT RELEASED as of this AOSP
// commit:
//https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+
// /b41bea65502ce7339665859d3c2c81b4a29194e4/java/src/com/android
// /inputmethod/latin/LatinIME.java
// so it can be assumed to affect all of KitKat released thus far
// (up to 4.4.2), and could even affect beyond KitKat, although I fully
// expect it to be incorporated into the next release *after* API level 19.
//
// When it IS released, this method should be changed to limit it to no
// higher than API level 19 (assuming that the fix is released before API
// level 20), just in order to limit the scope of this fix, since poking
// 1024 characters into the Editable object returned here is of course a
// kluge. But right now the safest thing is just to not have an upper limit
// on the application of this kluge, since the fix for the problem it
// addresses has not yet been released (as of 1/7/2014).
if(Build.VERSION.SDK_INT >= 14) {
if(myEditable == null) {
myEditable = new EditableAccomodatingLatinIMETypeNullIssues(
EditableAccomodatingLatinIMETypeNullIssues.ONE_UNPROCESSED_CHARACTER);
Selection.setSelection(myEditable, 1);
}
else {
int myEditableLength = myEditable.length();
if(myEditableLength == 0) {
//I actually HAVE seen this be zero on the Nexus 10 with the keyboard
// that came with Android 4.4.2
// On the Nexus 10 4.4.2 if I tapped away from the view and then back to it, the
// myEditable would come back as null and I would create a new one. This is also
// what happens on other devices (e.g., the Nexus 6 with 4.4.2,
// which has a slightly later version of the Google Keyboard). But for the
// Nexus 10 4.4.2, the keyboard had a strange behavior
// when I tapped on the rack, and then tapped Done on the keyboard to close it,
// and then tapped on the rack AGAIN. In THAT situation,
// the myEditable would NOT be set to NULL but its LENGTH would be ZERO. So, I
// just append to it in that situation.
myEditable.append(
EditableAccomodatingLatinIMETypeNullIssues.ONE_UNPROCESSED_CHARACTER);
Selection.setSelection(myEditable, 1);
}
}
return myEditable;
}
else {
//Default behavior for keyboards that do not require any fix
return super.getEditable();
}
}
//This method is called INSTEAD of generating a KEYCODE_DEL event, by
// versions of Latin IME that have the bug described in Issue 42904.
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
//If targetSdkVersion is set to anything AT or ABOVE API level 16
// then for the GOOGLE KEYBOARD versions DELIVERED
// with Android 4.1.x, 4.2.x or 4.3.x, NO KEYCODE_DEL EVENTS WILL BE
// GENERATED BY THE GOOGLE KEYBOARD (LatinIME) EVEN when TYPE_NULL
// is being returned as the InputType by your view from its
// onCreateInputMethod() override, due to a BUG in THOSE VERSIONS.
//
// When TYPE_NULL is specified (as this entire class assumes is being done
// by the views that use it, what WILL be generated INSTEAD of a KEYCODE_DEL
// is a deleteSurroundingText(1,0) call. So, by overriding this
// deleteSurroundingText() method, we can fire the KEYDOWN/KEYUP events
// ourselves for KEYCODE_DEL. This provides a workaround for the bug.
//
// The specific AOSP RELEASES involved are 4.1.1_r1 (the very first 4.1
// release) through 4.4_r0.8 (the release just prior to Android 4.4).
// This means that all of KitKat should not have the bug and will not
// need this workaround.
//
// Although 4.0.x (ICS) did not have this bug, it was possible to install
// later versions of the keyboard as an app on anything running 4.0 and up,
// so those versions are also potentially affected.
//
// The first version of separately-installable Google Keyboard shown on the
// Google Play store site by www.archive.org is Version 1.0.1869.683049,
// on June 6, 2013, and that version (and probably other, later ones)
// already had this bug.
//
//Since this required at least 4.0 to install, I believe that the bug will
// not be present on devices running versions of Android earlier than 4.0.
//
//AND, it should not be present on versions of Android at 4.4 and higher,
// since users will not "upgrade" to a version of Google Keyboard that
// is LOWER than the one they got installed with their version of Android
// in the first place, and the bug will have been fixed as of the 4.4 release.
//
// The above scope of the bug is reflected in the test below, which limits
// the application of the workaround to Android versions between 4.0.x and 4.3.x.
//
//UPDATE: A popular third party keyboard was found that exhibits this same issue. It
// was not fixed at the same time as the Google Play keyboard, and so the bug in that case
// is still in place beyond API LEVEL 19. So, even though the Google Keyboard fixed this
// as of level 19, we cannot take out the fix based on that version number. And so I've
// removed the test for an upper limit on the version; the fix will remain in place ad
// infinitum - but only when TYPE_NULL is used, so it *should* be harmless even when
// the keyboard does not have the problem...
if((Build.VERSION.SDK_INT >= 14) // && (Build.VERSION.SDK_INT < 19)
&& (beforeLength == 1 && afterLength == 0)) {
//Send Backspace key down and up events to replace the ones omitted
// by the LatinIME keyboard.
return super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
&& super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
}
else {
//Really, I can't see how this would be invoked, given that we're using
// TYPE_NULL, for non-buggy versions, but in order to limit the impact
// of this change as much as possible (i.e., to versions at and above 4.0)
// I am using the original behavior here for non-affected versions.
return super.deleteSurroundingText(beforeLength, afterLength);
}
}
}
接下来,取每个需要从 LatinIME 软键盘接收按键事件的 View 派生类,并编辑如下:
首先,在要接收关键事件的视图中创建对 onCreateInputConnection() 的覆盖,如下所示:
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
//Passing FALSE as the SECOND ARGUMENT (fullEditor) to the constructor
// will result in the key events continuing to be passed in to this
// view. Use our special BaseInputConnection-derived view
InputConnectionAccomodatingLatinIMETypeNullIssues baseInputConnection =
new InputConnectionAccomodatingLatinIMETypeNullIssues(this, false);
//In some cases an IME may be able to display an arbitrary label for a
// command the user can perform, which you can specify here. A null value
// here asks for the default for this key, which is usually something
// like Done.
outAttrs.actionLabel = null;
//Special content type for when no explicit type has been specified.
// This should be interpreted (by the IME that invoked
// onCreateInputConnection())to mean that the target InputConnection
// is not rich, it can not process and show things like candidate text
// nor retrieve the current text, so the input method will need to run
// in a limited "generate key events" mode. This disables the more
// sophisticated kinds of editing that use a text buffer.
outAttrs.inputType = InputType.TYPE_NULL;
//This creates a Done key on the IME keyboard if you need one
outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
return baseInputConnection;
}
其次,对视图的 onKey() 处理程序进行以下更改:
this.setOnKeyListener(new OnKeyListener() {
@Override public
boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() != KeyEvent.ACTION_DOWN) {
//We only look at ACTION_DOWN in this code, assuming that ACTION_UP is redundant.
// If not, adjust accordingly.
return false;
}
else if(event.getUnicodeChar() ==
(int)EditableAccomodatingLatinIMETypeNullIssues.ONE_UNPROCESSED_CHARACTER.charAt(0))
{
//We are ignoring this character, and we want everyone else to ignore it, too, so
// we return true indicating that we have handled it (by ignoring it).
return true;
}
//Now, just do your event handling as usual...
if(keyCode == KeyEvent.KEYCODE_ENTER) {
//Trap the Done key and close the keyboard if it is pressed (if that's what you want to do)
InputMethodManager imm = (InputMethodManager)
mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE));
imm.hideSoftInputFromWindow(LetterRack.this.getWindowToken(), 0);
return true;
}
else if(keyCode == KeyEvent.KEYCODE_DEL) {
//Backspace key processing goes here...
return true;
}
else if((keyCode >= KeyEvent.KEYCODE_A) && (keyCode <= KeyEvent.KEYCODE_Z)) {
//(Or, use event.getUnicodeChar() if preferable to key codes).
//Letter processing goes here...
return true;
}
//Etc. } };
最后,我们需要为可编辑对象定义一个类,以确保可编辑缓冲区中始终至少有一个字符:
import android.text.SpannableStringBuilder;
public class EditableAccomodatingLatinIMETypeNullIssues extends SpannableStringBuilder {
EditableAccomodatingLatinIMETypeNullIssues(CharSequence source) {
super(source);
}
//This character must be ignored by your onKey() code.
public static CharSequence ONE_UNPROCESSED_CHARACTER = "/";
@Override
public SpannableStringBuilder replace(final int
spannableStringStart, final int spannableStringEnd, CharSequence replacementSequence,
int replacementStart, int replacementEnd) {
if (replacementEnd > replacementStart) {
//In this case, there is something in the replacementSequence that the IME
// is attempting to replace part of the editable with.
//We don't really care about whatever might already be in the editable;
// we only care about making sure that SOMETHING ends up in it,
// so that the backspace key will continue to work.
// So, start by zeroing out whatever is there to begin with.
super.replace(0, length(), "", 0, 0);
//We DO care about preserving the new stuff that is replacing the stuff in the
// editable, because this stuff might be sent to us as a keydown event. So, we
// insert the new stuff (typically, a single character) into the now-empty editable,
// and return the result to the caller.
return super.replace(0, 0, replacementSequence, replacementStart, replacementEnd);
}
else if (spannableStringEnd > spannableStringStart) {
//In this case, there is NOTHING in the replacementSequence, and something is
// being replaced in the editable.
// This is characteristic of a DELETION.
// So, start by zeroing out whatever is being replaced in the editable.
super.replace(0, length(), "", 0, 0);
//And now, we will place our ONE_UNPROCESSED_CHARACTER into the editable buffer, and return it.
return super.replace(0, 0, ONE_UNPROCESSED_CHARACTER, 0, 1);
}
// In this case, NOTHING is being replaced in the editable. This code assumes that there
// is already something there. This assumption is probably OK because in our
// InputConnectionAccomodatingLatinIMETypeNullIssues.getEditable() method
// we PLACE a ONE_UNPROCESSED_CHARACTER into the newly-created buffer. So if there
// is nothing replacing the identified part
// of the editable, and no part of the editable that is being replaced, then we just
// leave whatever is in the editable ALONE,
// and we can be confident that there will be SOMETHING there. This call to super.replace()
// in that case will be a no-op, except
// for the value it returns.
return super.replace(spannableStringStart, spannableStringEnd,
replacementSequence, replacementStart, replacementEnd);
}
}
这完成了我发现似乎可以处理这两个问题的源代码更改。
附加说明:
问题 42904 描述的问题是在 API 级别 16 提供的 LatinIME 版本中引入的。在此之前,无论是否使用 TYPE_NULL,都会生成 KEYCODE_DEL 事件。在与 Jelly Bean 一起发布的 LatinIME 中,这一代已停产,但 TYPE_NULL 没有例外,因此针对 API 级别 16 以上的应用程序有效地禁用了 TYPE_NULL 行为。然而,添加了兼容性代码,允许具有targetSdkVersion < 16 继续接收 KEYCODE_DEL 事件,即使没有 TYPE_NULL。请参阅第 1493 行的此 AOSP 提交:
因此,您可以通过将应用程序中的 targetSdkVersion 设置为 15 或更低来解决此问题。
从提交 4.4_r0.9(就在 4.4 版本之前)开始,通过在保护 KEYCODE_DEL 生成的条件中添加对 isTypeNull() 的测试来解决此问题。不幸的是,一个新的错误 (62306) 正是在那个时候引入的,如果用户键入的退格键与键入其他字符的次数一样多,则会导致整个子句包装 KEYCODE_DEL 生成被跳过。这导致在这些情况下生成 KEYCODE_DEL 失败,即使使用 TYPE_NULL,甚至使用 targetSdkVersion <= 15。这导致以前能够通过兼容性代码 (targetSdkVersion <= 15) 获得正确 KEYCODE_DEL 行为的应用突然遇到这种情况当用户升级他们的 Google 键盘副本(或执行包含新版本 Google 键盘的 OTA)时出现问题。
此问题在 Google 键盘的已发布版本中一直存在到现在(2014 年 1 月 7 日)。它已在 repo 中修复,但在撰写本文时尚未发布。
可以在此处找到未发布的提交(包含此内容的 git 提交合并了一个标题为“当 TYPE_NULL 时发送退格作为事件”的提交),在第 2110 行(您可以看到用于阻止我们到达的子句的“NOT_A_CODE”子句生成 KEYCODE_DEL 已被删除):
发布此修复程序后,该版本的 Google 键盘将不再存在影响 TYPE_NULL 的这两个问题中的任何一个。 但是,在不确定的将来,特定设备上仍会安装旧版本。因此,该问题仍需要解决方法。最终,随着越来越多的人升级到比上一个不包括修复的更高级别,这种解决方法将越来越少。但它的范围已经被逐步淘汰(一旦您做出指示的更改以对范围设置最终限制,当最终修复实际上已发布以便您知道它实际上是什么时)。
(此答案是对 Carl 在此处发布的已接受答案的补充。)
虽然非常感谢对这两个错误的研究和理解,但我对 Carl 在此处发布的解决方法遇到了一些麻烦。我遇到的主要问题是,虽然卡尔的评论块说KeyEvent.ACTION_MULTIPLE
路径onKey()
只会在“选择信架后收到的第一个事件”上采用,但对我来说,每个关键事件都采用这条路径。(我通过查看BaseInputConnection.java
API-level-18 的代码发现这是因为每次都使用整个Editable
文本sendCurrentText()
。我不确定为什么它对 Carl 有效,但对我无效。)
因此,受卡尔的解决方案的启发,我对其进行了调整,使其不存在这个问题。我对问题 62306 的解决方案(链接到 Carl 的答案)试图达到相同的基本效果,即“欺骗”IME 使其认为总是有更多的文本可以退格。但是,它通过确保 Editable 中只有一个字符来做到这一点。为此,您需要以类似于以下的方式扩展实现Editable
接口的底层类:SpannedStringBuilder
private class MyEditable extends SpannableStringBuilder
{
MyEditable(CharSequence source) {
super(source);
}
@Override
public SpannableStringBuilder replace(final int start, final int end, CharSequence tb, int tbstart, int tbend) {
if (tbend > tbstart) {
super.replace(0, length(), "", 0, 0);
return super.replace(0, 0, tb, tbstart, tbend);
}
else if (end > start) {
super.replace(0, length(), "", 0, 0);
return super.replace(0, 0, DUMMY_CHAR, 0, 1);
}
return super.replace(start, end, tb, tbstart, tbend);
}
}
基本上,每当 IME 尝试向 Editable 添加字符(通过调用replace()
)时,该字符都会替换那里的任何单例字符。同时,如果 IME 尝试删除那里的内容,则replace()
覆盖会用单例“虚拟”字符(这应该是您的应用程序将忽略的内容)替换那里的内容,以保持长度为 1。
这意味着getEditable()
and的实现onKey()
可以比 Carl 上面发布的稍微简单一些。例如,假设MyEditable
上面的类被实现为一个内部类,getEditable()
就变成了这样:
@Override
public Editable getEditable() {
if (Build.VERSION.SDK_INT < 14)
return super.getEditable();
if (mEditable == null) {
mEditable = this.new MyEditable(DUMMY_CHAR);
Selection.setSelection(mEditable, 1);
}
else if (m_editable.length() == 0) {
mEditable.append(DUMMY_CHAR);
Selection.setSelection(mEditable, 1);
}
return mEditable;
}
请注意,使用此解决方案,无需维护 1024 个字符的长字符串。也没有“退格太多”的危险(正如卡尔关于按住退格键的评论中所讨论的那样)。
为了完整起见,onKey()
变为:
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() != KeyEvent.ACTION_DOWN)
return false;
if ((int)DUMMY_CHAR.charAt(0) == event.getUnicodeChar())
return true;
// Handle event/keyCode here as normal...
}
最后,我应该注意,以上所有内容都是仅发布 62306 的解决方法。我对 Carl (overriding) 发布的另一个问题 42904 的解决方案没有任何问题,deleteSurroundingText()
并建议在他发布时使用它。
介绍:
在测试了@Carl 和@Turix 的解决方案后,我注意到:
Carl 的解决方案不适用于 unicode 字符或字符序列,因为这些似乎是通过 ACTION_MULTIPLE 事件传递的,这使得很难区分“虚拟”字符和实际字符。
我无法deleteSurroundingText
在 Nexus 5 (4.4.2) 上使用最新版本的 Android。我针对几个不同的 sdk 版本进行了测试,但没有一个有效。也许谷歌决定再次改变 DEL 键背后的逻辑......
因此,我提出了以下组合解决方案,同时使用 Carl 和 Turix 的答案。我的解决方案通过结合 Carl 的长虚拟字符前缀的想法来使 DEL 工作,但使用 Turix 的自定义解决方案Editable
来生成正确的键事件。
结果:
我已经在几台具有不同版本的 Android 和不同键盘的设备上测试了这个解决方案。以下所有测试用例都对我有用。我还没有发现这个解决方案不起作用的情况。
我还针对不同的 sdk 版本进行了测试:
如果此解决方案也适用于您,那么请
风景:
public class MyInputView extends EditText implements View.OnKeyListener {
private String DUMMY;
...
public MyInputView(Context context) {
super(context);
init(context);
}
private void init(Context context) {
this.context = context;
this.setOnKeyListener(this);
// Generate a dummy buffer string
// Make longer or shorter as desired.
DUMMY = "";
for (int i = 0; i < 1000; i++)
DUMMY += "\0";
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
MyInputConnection ic = new MyInputConnection(this, false);
outAttrs.inputType = InputType.TYPE_NULL;
return ic;
}
@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
int action = keyEvent.getAction();
// Catch unicode characters (even character sequeneces)
// But make sure we aren't catching the dummy buffer.
if (action == KeyEvent.ACTION_MULTIPLE) {
String s = keyEvent.getCharacters();
if (!s.equals(DUMMY)) {
listener.onSend(s);
}
}
// Catch key presses...
if (action == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DEL:
...
break;
case KeyEvent.KEYCODE_ENTER:
...
break;
case KeyEvent.KEYCODE_TAB:
...
break;
default:
char ch = (char)keyEvent.getUnicodeChar();
if (ch != '\0') {
...
}
break;
}
}
return false;
}
}
输入连接:
public class MyInputConnection extends BaseInputConnection {
private MyEditable mEditable;
public MyInputConnection(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
}
private class MyEditable extends SpannableStringBuilder {
MyEditable(CharSequence source) {
super(source);
}
@Override
public SpannableStringBuilder replace(final int start, final int end, CharSequence tb, int tbstart, int tbend) {
if (tbend > tbstart) {
super.replace(0, length(), "", 0, 0);
return super.replace(0, 0, tb, tbstart, tbend);
}
else if (end > start) {
super.replace(0, length(), "", 0, 0);
return super.replace(0, 0, DUMMY, 0, DUMMY.length());
}
return super.replace(start, end, tb, tbstart, tbend);
}
}
@Override
public Editable getEditable() {
if (Build.VERSION.SDK_INT < 14)
return super.getEditable();
if (mEditable == null) {
mEditable = this.new MyEditable(DUMMY);
Selection.setSelection(mEditable, DUMMY.length());
}
else if (mEditable.length() == 0) {
mEditable.append(DUMMY);
Selection.setSelection(mEditable, DUMMY.length());
}
return mEditable;
}
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
// Not called in latest Android version...
return super.deleteSurroundingText(beforeLength, afterLength);
}
}
我遇到过类似的问题,即在触摸退格键时未收到 KEYCODE_DEL。这取决于我认为的软输入键盘,因为我的问题仅发生在某些第三方键盘(我认为是 swype)的情况下,而不是默认的谷歌键盘。
由于@Carl 的想法,我找到了一个适用于任何输入类型的解决方案。下面我给出了一个完整的工作示例应用程序,包括 2 个类:MainActivity
和CustomEditText
:
package com.example.edittextbackspace;
import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.view.ViewGroup.LayoutParams;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
CustomEditText edittext = initEditText();
setContentView(edittext);
}
private CustomEditText initEditText()
{
CustomEditText editText = new CustomEditText(this)
{
@Override
public void backSpaceProcessed()
{
super.backSpaceProcessed();
editTextBackSpaceProcessed(this);
}
};
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
editText.setText("1212");
return editText;
}
private void editTextBackSpaceProcessed(CustomEditText customEditText)
{
// Backspace event is called and properly processed
}
}
package com.example.edittextbackspace;
import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
public class CustomEditText extends EditText implements View.OnFocusChangeListener, TextWatcher
{
private String LOG = this.getClass().getName();
private int _inputType = 0;
private int _imeOptions = 5 | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
private List<String> _lastComposingTextsList = new ArrayList<String>();
private BaseInputConnection _inputConnection = null;
private String _lastComposingText = "";
private boolean _commitText = true;
private int _lastCursorPosition = 0;
private boolean _isComposing = false;
private boolean _characterRemoved = false;
private boolean _isTextComposable = false;
public CustomEditText(Context context)
{
super(context);
setOnFocusChangeListener(this);
addTextChangedListener(this);
}
@Override
public InputConnection onCreateInputConnection(final EditorInfo outAttrs)
{
CustomEditText.this._inputConnection = new BaseInputConnection(this, false)
{
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength)
{
handleEditTextDeleteEvent();
return super.deleteSurroundingText(beforeLength, afterLength);
}
@Override
public boolean setComposingText(CharSequence text, int newCursorPosition)
{
CustomEditText.this._isTextComposable = true;
CustomEditText.this._lastCursorPosition = getSelectionEnd();
CustomEditText.this._isComposing = true;
if (text.toString().equals(CustomEditText.this._lastComposingText))
return true;
else
CustomEditText.this._commitText = true;
if (text.length() < CustomEditText.this._lastComposingText.length())
{
CustomEditText.this._lastComposingText = text.toString();
try
{
if (text.length() > 0)
{
if (CustomEditText.this._lastComposingTextsList.size() > 0)
{
if (CustomEditText.this._lastComposingTextsList.size() > 0)
{
CustomEditText.this._lastComposingTextsList.remove(CustomEditText.this._lastComposingTextsList.size() - 1);
}
}
else
{
CustomEditText.this._lastComposingTextsList.add(text.toString().substring(0, text.length() - 1));
}
}
int start = Math.max(getSelectionStart(), 0) - 1;
int end = Math.max(getSelectionEnd(), 0);
CustomEditText.this._characterRemoved = true;
getText().replace(Math.min(start, end), Math.max(start, end), "");
}
catch (Exception e)
{
Log.e(LOG, "Exception in setComposingText: " + e.toString());
}
return true;
}
else
{
CustomEditText.this._characterRemoved = false;
}
if (text.length() > 0)
{
CustomEditText.this._lastComposingText = text.toString();
String textToInsert = Character.toString(text.charAt(text.length() - 1));
int start = Math.max(getSelectionStart(), 0);
int end = Math.max(getSelectionEnd(), 0);
CustomEditText.this._lastCursorPosition++;
getText().replace(Math.min(start, end), Math.max(start, end), textToInsert);
CustomEditText.this._lastComposingTextsList.add(text.toString());
}
return super.setComposingText("", newCursorPosition);
}
@Override
public boolean commitText(CharSequence text, int newCursorPosition)
{
CustomEditText.this._isComposing = false;
CustomEditText.this._lastComposingText = "";
if (!CustomEditText.this._commitText)
{
CustomEditText.this._lastComposingTextsList.clear();
return true;
}
if (text.toString().length() > 0)
{
try
{
String stringToReplace = "";
int cursorPosition = Math.max(getSelectionStart(), 0);
if (CustomEditText.this._lastComposingTextsList.size() > 1)
{
if (text.toString().trim().isEmpty())
{
getText().replace(cursorPosition, cursorPosition, " ");
}
else
{
stringToReplace = CustomEditText.this._lastComposingTextsList.get(CustomEditText.this._lastComposingTextsList.size() - 2) + text.charAt(text.length() - 1);
getText().replace(cursorPosition - stringToReplace.length(), cursorPosition, text);
}
CustomEditText.this._lastComposingTextsList.clear();
return true;
}
else if (CustomEditText.this._lastComposingTextsList.size() == 1)
{
getText().replace(cursorPosition - 1, cursorPosition, text);
CustomEditText.this._lastComposingTextsList.clear();
return true;
}
}
catch (Exception e)
{
Log.e(LOG, "Exception in commitText: " + e.toString());
}
}
else
{
if (!getText().toString().isEmpty())
{
int cursorPosition = Math.max(getSelectionStart(), 0);
CustomEditText.this._lastCursorPosition = cursorPosition - 1;
getText().replace(cursorPosition - 1, cursorPosition, text);
if (CustomEditText.this._lastComposingTextsList.size() > 0)
{
CustomEditText.this._lastComposingTextsList.remove(CustomEditText.this._lastComposingTextsList.size() - 1);
}
return true;
}
}
return super.commitText(text, newCursorPosition);
}
@Override
public boolean sendKeyEvent(KeyEvent event)
{
int keyCode = event.getKeyCode();
CustomEditText.this._lastComposingTextsList.clear();
if (keyCode > 60 && keyCode < 68 || !CustomEditText.this._isTextComposable || (CustomEditText.this._lastComposingTextsList != null && CustomEditText.this._lastComposingTextsList.size() == 0))
{
return super.sendKeyEvent(event);
}
else
return false;
}
@Override
public boolean finishComposingText()
{
if (CustomEditText.this._lastComposingTextsList != null && CustomEditText.this._lastComposingTextsList.size() > 0)
CustomEditText.this._lastComposingTextsList.clear();
CustomEditText.this._isComposing = true;
CustomEditText.this._commitText = true;
return super.finishComposingText();
}
@Override
public boolean commitCorrection(CorrectionInfo correctionInfo)
{
CustomEditText.this._commitText = false;
return super.commitCorrection(correctionInfo);
}
};
outAttrs.actionLabel = null;
outAttrs.inputType = this._inputType;
outAttrs.imeOptions = this._imeOptions;
return CustomEditText.this._inputConnection;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent)
{
if (keyCode == KeyEvent.KEYCODE_DEL)
{
int cursorPosition = this.getSelectionEnd() - 1;
if (cursorPosition < 0)
{
removeAll();
}
}
return super.onKeyDown(keyCode, keyEvent);
}
@Override
public void setInputType(int type)
{
CustomEditText.this._isTextComposable = false;
this._inputType = type;
super.setInputType(type);
}
@Override
public void setImeOptions(int imeOptions)
{
this._imeOptions = imeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
super.setImeOptions(this._imeOptions);
}
public void handleEditTextDeleteEvent()
{
int end = Math.max(getSelectionEnd(), 0);
if (end - 1 >= 0)
{
removeChar();
backSpaceProcessed();
}
else
{
removeAll();
}
}
private void removeAll()
{
int startSelection = this.getSelectionStart();
int endSelection = this.getSelectionEnd();
if (endSelection - startSelection > 0)
this.setText("");
else
nothingRemoved();
}
private void removeChar()
{
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL);
super.onKeyDown(event.getKeyCode(), event);
}
public void nothingRemoved()
{
// Backspace didn't remove anything. It means, a cursor of the editText was in the first position. We can use this method, for example, to switch focus to a previous view
}
public void backSpaceProcessed()
{
// Backspace is properly processed
}
@Override
protected void onSelectionChanged(int selStart, int selEnd)
{
if (CustomEditText.this._isComposing)
{
int startSelection = this.getSelectionStart();
int endSelection = this.getSelectionEnd();
if (((CustomEditText.this._lastCursorPosition != selEnd && !CustomEditText.this._characterRemoved) || (!CustomEditText.this._characterRemoved && CustomEditText.this._lastCursorPosition != selEnd)) || Math.abs(CustomEditText.this._lastCursorPosition - selEnd) > 1 || Math.abs(endSelection - startSelection) > 1)
{
// clean autoprediction words
CustomEditText.this._lastComposingText = "";
CustomEditText.this._lastComposingTextsList.clear();
CustomEditText.super.setInputType(CustomEditText.this._inputType);
}
}
}
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (!hasFocus) {
CustomEditText.this._lastComposingText = "";
CustomEditText.this._lastComposingTextsList.clear();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
int startSelection = getSelectionStart();
int endSelection = getSelectionEnd();
if (Math.abs(endSelection - startSelection) > 0)
{
Selection.setSelection(getText(), endSelection);
}
}
@Override
public void afterTextChanged(Editable s)
{
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
super.onTextChanged(s, start, before, count);
}
}
更新: 我更新了代码,因为在三星 Galaxy S6 等某些设备上启用文本预测时它无法正常工作(感谢@Jonas 他在下面的评论中告知了这个问题)并且使用 InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS 没有帮助这个案例。我在很多设备上测试了这个解决方案,但仍然不确定它是否适用于所有设备。如果 EditText 有任何不当行为,我希望我能得到您的一些评论。
我认为您可能会发现,如果您覆盖dispatchKeyEvent
适当的视图/活动的方法(在我的情况下,主要活动很好),您可以拦截密钥。
例如,我正在为具有硬件滚动键的设备开发应用程序,我惊讶地发现onKeyUp
/onKeyDown
方法从未被调用。相反,默认情况下,按键会经过一堆dispatchKeyEvent
s 直到它在某处调用滚动方法(在我的情况下,奇怪的是,一个按键会在两个单独的可滚动视图中的每一个上调用滚动方法 - 多么烦人)。
如果您检查退格字符的十进制数怎么办?
我认为它像'/r'(十进制数字7)或其他东西,至少对于ASCII。
编辑:我猜 Android 使用 UTF-8,所以这个十进制数是 8。 http://www.fileformat.info/info/unicode/char/0008/index.htm
鉴于 Umair 的回复,您可以考虑在此处应用解决方法:
捕获一个触摸事件,它不是一个键事件,并且在显示键盘时发生在屏幕的右下角。
希望有帮助
InputFilter 要求退格,如果 edittext 为空。
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if(source.equals("")) {
//a backspace was entered
}
return source;
}
}});
这是旧帖子,如果有人需要超级快速的破解/实施,请给出我的建议。
我想出的最简单的解决方法是实现 TextWatcher 以及 OnKeyListener 和onTextChanged与以前的现有字符串比较它是否减少了一个字符。
这样做的好处是它适用于任何类型的键盘,无需长时间的编码过程。
例如,我的 editText 只包含一个字符,所以我比较了characterSequence如果它是空字符串,那么我们可以确认按下了Delete 键。
下面是解释相同的代码:
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if(charSequence.toString().equals("")) //Compare here for any change in existing string by single character with previous string
{
//Carry out your tasks here it comes in here when Delete Key is pressed.
}
}
注意:在这种情况下,我的 edittext 仅包含单个字符,因此我将 charSequesnce 与空字符串进行比较(因为按 delete 将使其为空),根据您的需要,您需要对其进行修改和比较(就像在按下键子字符串后是原始字符串)它与现有字符串。希望能帮助到你。