Created
August 27, 2014 07:54
-
-
Save miensol/93a282b916e151c5216a to your computer and use it in GitHub Desktop.
Focus change listener that shows and hides soft keyboard programatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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