I'm building a simple Hangman app. I have currently set the keyBoard to hide after the user touches the submit button and restricted the EditText to a maxLength of "1".
What I want is for the Keyboard to hide right after the user touches a letter key and successfully inputs a valid entry into the EditText. I've tried implementing KeyEvent methods as used here and modified it to listen for any key code with the getMaxKeyCode() method.
UPDATE***: To clarify, I'm not having an issue with the ENTER button, that is working fine. I want the keyboard to hide after the user touches whichever letter they are guessing. So, if the user taps the 'E' key, the keyboard will hide as soon as the 'E' char appears in the EditText field.
Here's some of the code I'm using in the current iteration:
@OnClick(R.id.guess_button)
void submit() {
submitLetter();
}
private void submitLetter() {
Editable userInput = mGuessInput.getText();
String guessStr = mUserInput.toString();
if (mGuessStr.length() != 0) {
checkGuess(
String.valueOf(mGuessStr).charAt(0),
mCodeWord.toUpperCase()
);
mUserInput.clear();
mGuessInput.clearFocus();
hideKeyboard(MainActivity.this);
}
}
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if (view == null) {
view = new View(activity);
}
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
And here's what I'm trying to get to work:
public void hideKeyboardOnKeyTouch(EditText editText) {
final int generatedKeyCode = KeyEvent.getMaxKeyCode();
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event.getAction() == generatedKeyCode) {
hideKeyboard(MainActivity.this);
}
return false;
}
});
}
Then I call the above method on mGuessInput (the EditText View) in onCreate(). I've also tried checking for the ACTION_UP event in this method, but still nothing.
There's probably a simple solution that I'm missing but I think I'm not seeing the forest for the trees. I hope this isn't a duplicate, but I can't for the life of me find a solution for how to get this to work. Please help?