Skip to content

Instantly share code, notes, and snippets.

@mrleolink
Last active December 21, 2015 04:33
Show Gist options
  • Select an option

  • Save mrleolink/8823150 to your computer and use it in GitHub Desktop.

Select an option

Save mrleolink/8823150 to your computer and use it in GitHub Desktop.
A hack to catch events when soft keyboard comes up/down on Android (Tested on 2.3 and 4.0.4) (For usage: check out my blog post at: http://tech.leolink.net/2014/02/a-hack-to-catch-soft-keyboard-showhide.html)
public class SoftKeyboardHandledLinearLayout extends LinearLayout {
private boolean isKeyboardShown;
private SoftKeyboardVisibilityChangeListener listener;
public SoftKeyboardHandledLinearLayout(Context context) {
super(context);
}
public SoftKeyboardHandledLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@SuppressLint("NewApi")
public SoftKeyboardHandledLinearLayout(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
// Keyboard is hidden <<< RIGHT
if (isKeyboardShown) {
isKeyboardShown = false;
listener.onSoftKeyboardHide();
}
}
return super.dispatchKeyEventPreIme(event);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
final int actualHeight = getHeight();
if (actualHeight > proposedheight) {
// Keyboard is shown
if (!isKeyboardShown) {
isKeyboardShown = true;
listener.onSoftKeyboardShow();
}
} else {
// Keyboard is hidden <<< this doesn't work sometimes, so I don't use it
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void setOnSoftKeyboardVisibilityChangeListener(SoftKeyboardVisibilityChangeListener listener) {
this.listener = listener;
}
// Callback
public interface SoftKeyboardVisibilityChangeListener {
public void onSoftKeyboardShow();
public void onSoftKeyboardHide();
}
}
SoftKeyboardHandledLinearLayout mainView = (SoftKeyboardHandledLinearLayout) findViewById(R.id.main_view);
mainView.setOnSoftKeyboardVisibilityChangeListener(
new SoftKeyboardVisibilityChangeListener() {
@Override
public void onSoftKeyboardShow() {
// TODO: do something here
}
@Override
public void onSoftKeyboardHide() {
// TODO: do something here
}
});
@KennethYo
Copy link

Thank you,in my app,work nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment