网上看了不少关于软键盘的显示操作,这里自己也做一下记录。
步骤1.重写布局,在onLayout中设置监听
public class MyKeyBoardLinearLayout extends LinearLayout {
private OnSoftKeyboardListener mSoftKeyboardListener;
public MyKeyBoardLinearLayout(@NonNull Context context) {
super(context);
}
public MyKeyBoardLinearLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyKeyBoardLinearLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public interface OnSoftKeyboardListener{
void onSoftKeyboardChange();
}
public void setSoftKeyboardListener(OnSoftKeyboardListener listener){
mSoftKeyboardListener=listener;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mSoftKeyboardListener != null)
mSoftKeyboardListener.onSoftKeyboardChange();
}
}
步骤2. 判断尺度大小
public boolean isSoftKeyboardShow(View rootView) {
int screenHeight;
screenHeight = getResources().getDisplayMetrics().heightPixels;
Rect rect = new Rect();
rootView.getWindowVisibleDisplayFrame(rect);
int visibleBottom = rect.bottom;
return visibleBottom < screenHeight * 2 / 3;
}
步骤3. 进行监听
mLlRoot.setSoftKeyboardListener(() -> {
boolean isShow = isSoftKeyboardShow(mLlRoot);
if (isShow) {
UIUtils.showToast("展示");
} else {
UIUtils.showToast("隐藏");
}
});