Android监听软键盘收起与弹出
2018-05-10 本文已影响37人
刘小厨
在项目中有时候会需要监听软键盘的弹出与收起,并没有找到官方的API,所以根据网上的思路,自定义View来实现监听.
并不复杂直接上代码吧:
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
public class MeasuredLayout extends LinearLayout {
private int largestHeight;
private OnKeyboardHideListener onKeyboardHideListener;
private int heightPrevious;
private int heightNow;
private View mChildOfContent;
private int usableHeightPrevious;
public MeasuredLayout(Context context, View view){
super(context);
addView(view);
}
public MeasuredLayout(Context context, AttributeSet attrs, int layoutId) {
super(context, attrs);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(layoutId, this);
mChildOfContent=getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard / 4)) {
// 键盘弹出
if (onKeyboardHideListener != null) {
onKeyboardHideListener.onKeyboardHide(false);
}
} else {
// 键盘收起
if (onKeyboardHideListener != null) {
onKeyboardHideListener.onKeyboardHide(true);
}
}
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
return (r.bottom - r.top);
}
public interface OnKeyboardHideListener {
void onKeyboardHide(boolean hide);
}
public void setOnKeyboardHideListener(OnKeyboardHideListener onKeyboardHideListener) {
this.onKeyboardHideListener = onKeyboardHideListener;
}
}
使用的时候很简单:
只需要
public View getContentView() {
MeasuredLayout measuredLayout = new MeasuredLayout(this, null, R.layout.activity_apply_cash);
measuredLayout.setOnKeyboardHideListener(this);
return measuredLayout;
}
将该方法返回的View塞给Activity的 setContentView();方法.
并在使用监听的Activity实现MeasuredLayout.OnKeyboardHideListener 接口并重写方法
@Override
public void onKeyboardHide(boolean hide) {
isKeyboardHide=hide;
if(hide){
//这里我们就可以拿到软键盘是否隐藏了
}
}
``