Skip to content

Instantly share code, notes, and snippets.

@turastory
Created February 22, 2018 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turastory/6904ded5c14a60af23171003d0d40150 to your computer and use it in GitHub Desktop.
Save turastory/6904ded5c14a60af23171003d0d40150 to your computer and use it in GitHub Desktop.
Use of onKeyPreIme
/**
* Does not hide the keyboard when back key pressed
* and perform specified action that provided by Listener.
*/
public class ConstantEditText extends AppCompatEditText {
public interface OnBackKeyListener {
void onBackKeyPressed();
}
private OnBackKeyListener onBackKeyListener;
/**
* Use AtomicBoolean to ensure thread safe.
*/
private AtomicBoolean onKeyPreImeBlock = new AtomicBoolean(false);
public ConstantEditText(Context context) {
super(context);
}
public ConstantEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ConstantEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public OnBackKeyListener getOnBackKeyListener() {
return onBackKeyListener;
}
public void setOnBackKeyListener(OnBackKeyListener onBackKeyListener) {
this.onBackKeyListener = onBackKeyListener;
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (onKeyPreImeBlock.get())
return true;
// Ensure that the lines of code below (handling KEYCODE_BACK) execute only once in 100ms
// So callback should call only once.
onKeyPreImeBlock.set(true);
postDelayed(() -> onKeyPreImeBlock.set(false), 100);
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (onBackKeyListener != null) {
onBackKeyListener.onBackKeyPressed();
}
return true;
}
return super.onKeyPreIme(keyCode, event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment