-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathKeyboardUtil.java
More file actions
64 lines (54 loc) · 2.22 KB
/
KeyboardUtil.java
File metadata and controls
64 lines (54 loc) · 2.22 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
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 {
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);
imm.hideSoftInputFromWindow(editText.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
editText.clearFocus();
}
public static boolean isKeyboardVisible(final Activity activity, final EditText editText) {
if (activity == null || editText == null) {
return false;
}
final InputMethodManager imm = ContextCompat.getSystemService(activity,
InputMethodManager.class);
return imm.isActive(editText);
}
}