簡體   English   中英

Android-無法捕獲軟件中的退格鍵/刪除鍵。 鍵盤

[英]Android - cannot capture backspace/delete press in soft. keyboard

我覆蓋了視圖(openGL表面視圖)的onKeyDown方法以捕獲所有按鍵。 問題是在多個設備上沒有捕獲KEYCODE_DEL。 我嘗試將onKeyListener添加到視圖中,並且捕獲了除Backspace鍵之外的所有內容。

必須有一種方法來監聽此按鍵事件,但是如何?

2014年11月12日更新:已將修復范圍更改為不限於<API級別19,因為第三方鍵盤上的錯誤仍超過19。

2014年1月9日更新:我已經設計出一種帶有代碼的方法來解決所有Google鍵盤(LatinIME)KEYCODE_DEL問題,尤其是問題42904和62306。

Turix的答案的增強功能已在獲得許可的情況下並入我自己的代碼中 Turix的改進消除了將垃圾字符注入Editable緩沖區的麻煩,而改為尋找一種增量方式來確保該緩沖區中始終有一個字符。

我在一個已部署的應用程序中使用了與此類似的代碼,歡迎您進行測試:
https://play.google.com/store/apps/details?id=com.goalstate.WordGames.FullBoard.trialsuite]

介紹:

就這兩個錯誤而言,下面介紹的解決方法旨在適用於過去和將來的所有版本的Google Keyboard。 這種解決方法並不需要一個應用程序仍然卡住定位API級別15或以下,其中一些應用程序,以便采取的圍繞問題42904獲取兼容性代碼的優勢有限制自己。

這些問題僅作為已實現onCreateInputConnection()重寫的視圖的bug出現並且該視圖將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的問題是,由於兩個已知的bug,報告如下

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)提交,在該提交中引入了兩個錯誤,在此錯誤中又消失了,以及可能包括受影響的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);
   }
 }

這樣就完成了我發現可以解決這兩個問題的源代碼更改。

其他說明

在API級別16隨附的LatinIME版本中引入了問題42904描述的問題。在此之前,無論是否使用TYPE_NULL都將生成KEYCODE_DEL事件。 在與Jelly Bean一起發布的LatinIME中,這一代產品已經停產,但是TYPE_NULL沒有例外,因此,針對API級別16以上的應用有效地禁用了TYPE_NULL行為。但是,添加了兼容性代碼,允許具有targetSdkVersion <16,即使沒有TYPE_NULL,也繼續接收KEYCODE_DEL事件。 請參閱第1493行的AOSP提交:

https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/android-4.1.1_r1/java/src/com/android/inputmethod/latin/LatinIME.java

因此,可以通過將應用程序中的targetSdkVersion設置為15或更低的值來解決此問題。

從commit 4.4_r0.9開始(僅在4.4版本之前),已通過在保護KEYCODE_DEL生成的條件中添加isTypeNull()測試來解決此問題。 不幸的是,正是在這一點上引入了一個新的錯誤(62306),如果用戶鍵入退格次數與鍵入其他字符的次數相同,則會導致包裝KEYCODE_DEL代的整個子句被跳過。 在這種情況下,即使使用TYPE_NULL,甚至使用targetSdkVersion <= 15,也無法生成KEYCODE_DEL。這導致以前能夠通過兼容性代碼(targetSdkVersion <= 15)獲得正確KEYCODE_DEL行為的應用突然遇到這種情況。用戶升級其Google鍵盤副本(或執行包含新版Google鍵盤的OTA)時出現問題。 請參閱第2146行的AOSP git文件(包括“ NOT_A_CODE”的子句):

https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/android-4.4_r0.9/java/src/com/android/inputmethod/latin/LatinIME.java

到目前為止,此問題在發行版的Google鍵盤中仍然存在(2014年1月7日)。 它已在存儲庫中修復,但截至本文撰寫時尚未發布。

可以在此處找到未發布的提交(包含該提交的git提交將名為“ TYPE_NULL時將退格作為事件發送退格”的提交合並)在第2110行(您可以看到“ NOT_A_CODE”子句用於防止我們到達該子句)生成KEYCODE_DEL已被刪除):

https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/b41bea65502ce7339665859d3c2c81b4a29194e4/java/src/com/android/inputmethod/latin/LatinIME.java

發布此修復程序后,該版本的Google鍵盤將不再具有影響TYPE_NULL的這兩個問題。 但是 ,在不確定的將來,仍將在特定設備上安裝較舊的版本。 因此,該問題仍將需要解決方法。 最終,隨着更多人升級到更高的級別而不是上一個不包含此修復程序的人,將越來越需要這種解決方法。 但是它已經可以逐步淘汰(一旦您進行了指示性的更改以將最終限制放到范圍上,而最終修訂實際上已經發布,以便您知道它的真正含義)。

看起來像是Android的錯誤:

問題42904 :KEYCODE_DEL事件未傳遞到SDK 16及更高版本中的EditText

發行42904 @ code.google.com

介紹:

在測試了@Carl和@Turix的解決方案之后,我注意到:

  1. Carl的解決方案不適用於Unicode字符或字符序列,因為它們似乎是與ACTION_MULTIPLE事件一起提供的,這使得很難區分“虛擬”字符和實際字符。

  2. 我無法在Nexus 5(4.4.2)的最新版本的Android中使用deleteSurroundingText 我針對幾種不同的sdk版本進行了測試,但沒有一個起作用。 也許Google已經決定再次更改DEL鍵背后的邏輯...

因此,我使用了卡爾和Turix的答案,提出了以下組合解決方案。 我的解決方案通過結合卡爾關於長假字符前綴的想法使DEL起作用,但是將Turix的解決方案用於自定義Editable來生成適當的鍵事件。

結果:

我已經在具有不同版本Android和不同鍵盤的多種設備上測試了該解決方案。 以下所有測試用例都對我有用。 我還沒有發現這種解決方案不起作用的情況。

  • 具有標准Google鍵盤的Nexus 5(4.4.2)
  • 具有SwiftKey的Nexus 5(4.4.2)
  • 配備標准HTC鍵盤的HTC One(4.2.2)
  • 具有標准Google鍵盤的Nexus One(2.3.6)
  • 帶有標准三星鍵盤的三星Galaxy S3(4.1.2)

我還針對不同的SDK版本進行了測試:

  • 目標16
  • 目標19

如果此解決方案也對您有效,請

風景:

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

(此答案是卡爾在此處發布的公認答案的附錄。)

雖然非常贊賞對這兩個bug的研究和理解,但我對Carl在此處發布的解決方法有一些麻煩。 我遇到的主要問題是,盡管卡爾的注釋塊說onKey()中的KeyEvent.ACTION_MULTIPLE路徑僅在“選擇字母架后收到的第一個事件”上采用,但對我來說,每個單個鍵事件都采用該路徑。 (我通過查看API級別18的BaseInputConnection.java代碼發現,這是因為每次都在sendCurrentText()使用了整個Editable文本。我不確定為什么它對Carl有效,但對我卻不起作用。)

因此,受卡爾解決方案的啟發,我對其進行了調整,以解決這個問題。 我對問題62306的解決方案(與卡爾的答案相關聯)試圖實現“誘使” 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()替代會使用單例“虛擬”字符(您的應用程序將忽略的字符replace()替換那里的內容,以保持1的長度。

這意味着getEditable()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()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發布的另一個問題42904的解決方案沒有任何問題(覆蓋deleteSurroundingText() ),並且建議在發布時使用它。

我曾遇到過類似的問題,即在按Backspace鍵時未收到KEYCODE_DEL。 這取決於我認為的軟輸入鍵盤,因為我的問題僅在某些第三方鍵盤(我認為是Swype)的情況下發生,而不是默認的Google鍵盤。

由於@Carl的想法,我想到了一種適用於任何輸入類型的解決方案。 下面,我給出一個完整的工作示例應用程序,該應用程序包含2個類: MainActivityCustomEditText

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

更新:我更新了代碼,因為在諸如Samsung Galaxy S6之類的某些設備上啟用了文本預測時,它無法正常工作(感謝@Jonas他在下面的評論中告知了此問題)並使用InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS在這個案例。 我在許多設備上測試了該解決方案,但仍不確定該解決方案是否對所有設備都適用。 如果EditText有任何不當行為,希望我能給您一些評論。

我認為您可能會發現,如果重寫適當的視圖/活動的dispatchKeyEvent方法(在我的情況下,主活動很好),則可以攔截該鍵。

例如,我正在為具有硬件滾動鍵的設備開發應用程序,但我驚訝地發現onKeyUp / onKeyDown方法從未被調用過。 取而代之的是,默認情況下,按鍵會經過一堆dispatchKeyEvent直到它在某個地方調用了滾動方法(在我的情況下,非常奇怪的是,一次按鍵在兩個單獨的可滾動視圖中的每個上都調用了一個滾動方法-多么令人討厭)。

如果您檢查退格字符的十進制數字該怎么辦?

我認為它類似於“ / r”(十進制數7)之類的東西,至少對於ASCII而言。

編輯:我想Android使用UTF-8,所以此十進制數將是8。http ://www.fileformat.info/info/unicode/char/0008/index.htm

鑒於Umair的回應,您可以考慮在此處應用解決方法:

捕獲不是鍵盤事件的觸摸事件,而是在顯示鍵盤時在屏幕的右下部分附近發生。

如何在Android中獲得Touch位置?

是否可以判斷是否顯示了軟鍵盤?

希望能有所幫助

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

這是舊文章,如果有人需要超級快速的破解/實施 ,請提供我的建議

我想到的最簡單的方法是在OnKeyListener上也實現TextWatcher,並在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會使它為空),根據您的需要,您需要對其進行修改和比較(就像按子字符串一樣,是原始字符串)與現有字符串一起使用。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM