Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.