键盘显示,隐藏的事件监听。

activity 中 监听 键盘的显示,隐藏, 需要自定义LinearLayout.

public class ResizeLayout extends LinearLayout {
private OnResizeListener mListener;

public interface OnResizeListener {
void OnResize(int w, int h, int oldw, int oldh);
}

public void setOnResizeListener(OnResizeListener l) {
mListener = l;
}

public ResizeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);

if (mListener != null) {
mListener.OnResize(w, h, oldw, oldh);
}
}
}

监听onResize 的回调。
在全屏状态下,回调不起作用, AndroidBug5497Workaround 解决。

public class AndroidBug5497Workaround {
private keywordShowHide listener;
//全屏下键盘事件不影响布局改变
// For more information, see https://code.google.com/p/android/issues/detail?id=5497
// To use this class, simply invoke assistActivity() on an Activity that already has its content view set.


private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;

public AndroidBug5497Workaround(Activity activity,keywordShowHide listener) {
this.listener = listener;
FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
}

private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard/4)) {
// keyboard probably just became visible
if(listener!=null){
listener.show();
}
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
} else {
// keyboard probably just became hidden
if(listener!=null){
listener.hide();
}
frameLayoutParams.height = usableHeightSansKeyboard;

mChildOfContent.requestLayout();
}
usableHeightPrevious = usableHeightNow;
}
}

private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
return (r.bottom - r.top);
}


public interface keywordShowHide{
public void show();
public void hide();
}

}
原文地址:https://www.cnblogs.com/songsh/p/6525847.html