android 监听软键盘弹起和关闭状态与点击空白区域软键盘隐藏

时间:2022-03-27 02:00:41

监听软键盘弹起与关闭状态 

很多例子上用的是大于100去判断,现在手机屏幕越来越大,分辨率越来越高,100的高度是不够的

view.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
view.getWindowVisibleDisplayFrame(r);
int screenHeight = view.getRootView()
.getHeight();
int heightDifference = screenHeight - (r.bottom);
if (heightDifference > 200) {
//软键盘显示
mIsSoftKeyboardShowing = true;
Log.e("TAG", "显示");
} else {
//软键盘隐藏
Log.e("TAG", "隐藏");
mIsSoftKeyboardShowing = false;

}
}

});



第二种写法:监听软键盘弹起与关闭状态

不需要去界面里面写判断,定义一个 类实现ViewTreeObserver.OnGlobalLayoutListener,并在这里面做判断

package com.dreamlive.utils;

import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;

/**
* 软键盘显示与隐藏监听
*
* @author 2017/7/7 / mengwei
*/
public class OnKeyboardChangeListener implements ViewTreeObserver.OnGlobalLayoutListener {

private View mContainer;
private OnChangeListener mOnChangerListener;

public OnKeyboardChangeListener(View view, OnChangeListener onChangeListener) {
mContainer = view;
mOnChangerListener = onChangeListener;
}

@Override
public void onGlobalLayout() {
if (mOnChangerListener != null) {
Rect rect = new Rect();
mContainer.getWindowVisibleDisplayFrame(rect);
int heightDifference = mContainer.getRootView().getHeight() - rect.bottom;
if (heightDifference > 200) {
mOnChangerListener.onKeyboardShow();
} else {
mOnChangerListener.onKeyboardHidden();
}
}
}

/**
* 软键盘监听变化接口
*/
public interface OnChangeListener {
void onKeyboardShow();//显示接口

void onKeyboardHidden();//隐藏接口
}
}

在界面实现onChangeListener接口

    @Override
public void onKeyboardShow() {
Log.e("Tag", "show");
mIsSoftKeyboardShowing = true;
}

@Override
public void onKeyboardHidden() {
Log.e("Tag", "hidden");
mIsSoftKeyboardShowing = false;
}

调用,view是editText的父布局

 view.getViewTreeObserver().addOnGlobalLayoutListener(new OnKeyboardChangeListener(view, this));


****************************点击空白区域软键盘隐藏*************************************

   boolean mIsSoftKeyboardShowing = false;

@Override
public boolean onTouchEvent(MotionEvent event) {
if (mIsSoftKeyboardShowing) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
}
return true;
} else {
return super.onTouchEvent(event);
}
}



ok,结束了,仅做记录用。