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
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.