KeyboardHelper.java
3.57 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.wd.comment.utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* @author LiuKun
* @date 2023/5/2 16:58
* @Description:对软键盘的操作
*/
public class KeyboardHelper {
/**
* 编辑框获取焦点,并显示软件盘
*/
public static void showSoftInput(View view) {
if (view == null) {
return;
}
view.requestFocus();
InputMethodManager manager = (InputMethodManager) view.getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
manager.showSoftInput(view, 0);
}
/**
* 隐藏软件盘
*/
public static void hideSoftInput(View view) {
if (view == null) {
return;
}
InputMethodManager manager = (InputMethodManager) view.getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
* 是否显示软件盘
*
* @return
*/
public static boolean isSoftInputShown(Activity activity) {
return getSupportSoftInputHeight(activity) != 0;
}
/**
* 获取软件盘的高度
*
* @return
*/
private static int getSupportSoftInputHeight(Activity activity) {
Rect r = new Rect();
/**
* decorView是window中的最顶层view,可以从window中通过getDecorView获取到decorView。
* 通过decorView获取到程序显示的区域,包括标题栏,但不包括状态栏。
*/
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
//获取屏幕的高度
int screenHeight = activity.getWindow().getDecorView().getRootView().getHeight();
//计算软件盘的高度
int softInputHeight = screenHeight - r.bottom;
/**
* 某些Android版本下,没有显示软键盘时减出来的高度总是144,而不是零,
* 这是因为高度是包括了虚拟按键栏的(例如华为系列),所以在API Level高于20时,
* 我们需要减去底部虚拟按键栏的高度(如果有的话)
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
// When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
softInputHeight = softInputHeight - getSoftButtonsBarHeight(activity);
}
if (softInputHeight < 0) {
Log.d("123", "EmotionKeyboard--Warning: value of softInputHeight is below zero!");
}
return softInputHeight;
}
/**
* 底部虚拟按键栏的高度
*
* @return
*/
private static int getSoftButtonsBarHeight(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
//这个方法获取可能不是真实屏幕的高度
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int usableHeight = metrics.heightPixels;
//获取当前屏幕的真实高度
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
}
int realHeight = metrics.heightPixels;
if (realHeight > usableHeight) {
return realHeight - usableHeight;
} else {
return 0;
}
}
}