Skip to content

Instantly share code, notes, and snippets.

@btow
Created July 6, 2018 07:29
Show Gist options
  • Save btow/2eb42b1f1da3bb80e9f8de5e599957e5 to your computer and use it in GitHub Desktop.
Save btow/2eb42b1f1da3bb80e9f8de5e599957e5 to your computer and use it in GitHub Desktop.
The class for controll of a keyboard
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.util.Objects;
@android.support.annotation.VisibleForTesting()
public class KeyboardsController {
private static final long UI_UPDATE_DELAY = 1000l;
private static InputMethodManager mInputManager = null;
public static void hideKeyboard(@NonNull final Context cxt) {
// check if no view has focus:
View v = ((Activity) cxt).getCurrentFocus();
if (v == null)
return;
mInputManager = (InputMethodManager) cxt
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (mInputManager != null) {
mInputManager.showSoftInput(v, InputMethodManager.HIDE_NOT_ALWAYS);
Objects.requireNonNull(mInputManager).hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
public static void showSoftInput(@NonNull final Context cxt, final EditText editText) {
mInputManager = (InputMethodManager) cxt
.getSystemService(Context.INPUT_METHOD_SERVICE);
editText.postDelayed(() -> {
if (mInputManager != null) {
mInputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, UI_UPDATE_DELAY);
editText.requestFocus();
}
@android.support.annotation.VisibleForTesting()
public static InputMethodManager getInputManager(){
return mInputManager;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment