-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathKeyboardUtil.java
More file actions
65 lines (53 loc) · 2.18 KB
/
KeyboardUtil.java
File metadata and controls
65 lines (53 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package org.schabi.newpipe.util;
import android.app.Activity;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import androidx.core.content.ContextCompat;
/**
* Utility class for the Android keyboard.
* <p>
* See also <a href="https://stackoverflow.com/q/1109022">https://stackoverflow.com/q/1109022</a>
* </p>
*/
public final class KeyboardUtil {
/**
* Flag for {@link #hideKeyboard(Activity, EditText)} to force the keyboard to hide.
* This is required for non-touch devices like Fire TV where the system
* flags the focus as an explicit user action.
*/
private static final int CLEAR_SOFT_INPUT_FORCED = 0;
private KeyboardUtil() {
}
public static void showKeyboard(final Activity activity, final EditText editText) {
if (activity == null || editText == null) {
return;
}
if (editText.requestFocus()) {
final InputMethodManager imm = ContextCompat.getSystemService(activity,
InputMethodManager.class);
if (!imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED)) {
/*
* Sometimes the keyboard can't be shown because Android's ImeFocusController is in
* a incorrect state e.g. when animations are disabled or the unfocus event of the
* previous view arrives in the wrong moment (see #7647 for details).
* The invalid state can be fixed by to re-focusing the editText.
*/
editText.clearFocus();
editText.requestFocus();
// Try again
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
}
}
}
public static void hideKeyboard(final Activity activity, final EditText editText) {
if (activity == null || editText == null) {
return;
}
final InputMethodManager imm = ContextCompat.getSystemService(activity,
InputMethodManager.class);
if (imm != null) {
imm.hideSoftInputFromWindow(editText.getWindowToken(), CLEAR_SOFT_INPUT_FORCED);
}
editText.clearFocus();
}
}