Skip to content

Instantly share code, notes, and snippets.

@miensol
Created August 27, 2014 07:54
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 miensol/93a282b916e151c5216a to your computer and use it in GitHub Desktop.
Save miensol/93a282b916e151c5216a to your computer and use it in GitHub Desktop.
Focus change listener that shows and hides soft keyboard programatically
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class KeyboardManagingFocusListener implements View.OnFocusChangeListener {
private final EditText editText;
public KeyboardManagingFocusListener(EditText editText) {
this.editText = editText;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
setImeVisibility(hasFocus);
}
private Runnable mShowImeRunnable = new Runnable() {
public void run() {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(editText,0);
}
}
};
private Context getContext() {
return editText.getContext();
}
private void setImeVisibility(final boolean visible) {
if (visible) {
editText.post(mShowImeRunnable);
} else {
editText.removeCallbacks(mShowImeRunnable);
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment