When the soft keyboard appears, it makes my EditText field lose focus

后端 未结 11 1790
名媛妹妹
名媛妹妹 2020-12-07 10:19

I\'ve got a few EditText fields in a ListView. When I tap on one of the EditText fields, the keyboard slides into view (as it should), but the EditText field I tapped loses

11条回答
  •  隐瞒了意图╮
    2020-12-07 10:38

    Here is how I did it. The onFocusChangeListener() is called several times when you touch a EditText to type text into it. The sequence is:

    1. If focus was on a different view, then that view loses focus
    2. The target gains focus
    3. Soft keyboard pops up.
    4. This causes the target to lose focus
    5. The code detects this situation and calls target.requestFocus()
    6. The leftmost, topmost view gains focus, due to Android nonsense
    7. The leftmost view loses focus, due to requestFocus being called
    8. Target finally gains focus

      //////////////////////////////////////////////////////////////////
      private final int minDelta = 300;           // threshold in ms
      private long focusTime = 0;                 // time of last touch
      private View focusTarget = null;
      
      View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View view, boolean hasFocus) {
              long t = System.currentTimeMillis();
              long delta = t - focusTime;
              if (hasFocus) {     // gained focus
                  if (delta > minDelta) {
                      focusTime = t;
                      focusTarget = view;
                  }
              }
              else {              // lost focus
                  if (delta <= minDelta  &&  view == focusTarget) {
                      focusTarget.post(new Runnable() {   // reset focus to target
                          public void run() {
                              focusTarget.requestFocus();
                          }
                      });
                  }
              }
          }
      };
      

    The code above works well for the keyboard pop-ups. However, it does not detect the speech-to-text pop-up.

提交回复
热议问题