Android SoftKeyboard onKeyDown/Up not detecting 'alternative' keys

前端 未结 3 683
忘了有多久
忘了有多久 2020-12-19 15:50

I have a view which handles input for me, I pop up a keyboard and set the view focusable. Now I can get certain key presses...

@Override
public boolean onKey         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 16:28

    When the keyboard is open, onKeyDown() and onKeyUp() methods don't work properly because Android considers on-screen keyboard as a separate activity.

    The easiest way to achieve what you want is to override onKeyPreIme() method on your view. For example, if you're trying to capture onKeyDown from an EditText, create a new Class which extends EditText, and override the onKeyPreIme() method:

    public class LoseFocusEditText extends EditText {
    
        private Context mContext;
    
        protected final String TAG = getClass().getName();
    
        public LoseFocusEditText(Context context) {
            super(context);
            mContext = context;
        }
    
        public LoseFocusEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            mContext = context;
        }
    
        public LoseFocusEditText(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            mContext = context;
        }
    
        @Override
        public boolean onKeyPreIme(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
    
                //hide keyboard
                InputMethodManager mgr = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                mgr.hideSoftInputFromWindow(this.getWindowToken(), 0);
    
                //lose focus
                this.clearFocus();
    
                return true;
            }
            return false;
        }
    }
    

    This was tested on kitkat / htc one.

提交回复
热议问题