键盘相关

SoftInputUtil软键盘隐藏or显示

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
public class SoftInputUtil {
/**
* 显示软键盘
*
* @param context
*/
public static void showSoftInput(Context context) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}

/**
* 显示软键盘
*
* @param context
* @param view
*/
public static void showSoftInput(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, 0);
}

/**
* 隐藏软键盘
*
* @param context
* @param view
*/
public static void hideSoftInput(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}

键盘相关代码

获取键盘高度

1
2
3
4
5
6
7
private int getKeyboardHight(View rootView){
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff;
}

监听键盘弹出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private boolean isKeyboardShow(View rootView){
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}

view.getRootView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener){
@Ovrride
public void onGlobalLayout(){
recyclerView.scrollToPosition(recyclerView.getAdapter().getItemtCount() - 1);
}
}

当加入沉浸式时,在AndroidManifest中设置android:windowSoftInputMode="stateUnspecified|adjustUnspecified"失效

在代码onCreate()#setContentView()之后加入getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
(使用getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);不可以)