Android官方本身没有提供一共好的方法来对软键盘进行监听,但我们实际应用时,很多地方都需要针对软键盘来对UI进行一些优化。
以下是整理出来的一个不错的方法,大家可以使用。
不过要注意的是,由于是使用ViewTreeObserver来进行监听,所以每次layout有所改变的话,都会触发,所以listner里面如果有改变layout的方法的话,要注意不要陷入无限触发循环了,这时需要加入一些标记值来规避,这个可以参考代码注释
public class SoftKeyboardUtil {
public static final String TAG = "SoftKeyboardUtil";
public static void observeSoftKeyboard(Activity activity, final OnSoftKeyboardChangeListener listener) {
final View decorView = activity.getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int displayHeight = rect.bottom - rect.top;
int height = decorView.getHeight();
boolean hide = (double) displayHeight / height > 0.8;
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "DecorView display hight = " + displayHeight);
Log.d(TAG, "DecorView hight = " + height);
Log.d(TAG, "softkeyboard visible = " + !hide);
}
listener.onSoftKeyBoardChange(height - displayHeight, !hide);
}
});
}
/**
* Note: if you change layout in this method, maybe this method will repeat because the ViewTreeObserver.OnGlobalLayoutListener will repeat So maybe you need do some handle(ex: add some flag to avoid repeat) in this callback
*
* Example:
*
* private int previousHeight = -1; private void setupKeyboardLayoutWhenEdit() { SoftKeyboardUtil.observeSoftKeyBoard(this, new OnSoftKeyboardChangeListener() {
*
* @Override public void onSoftKeyBoardChange(int softkeybardHeight, boolean visible) { if (previousHeight == softkeybardHeight) { return; } previousHeight = softkeybardHeight; //code for change layout } }); }
*
*
*
*/
public interface OnSoftKeyboardChangeListener {
void onSoftKeyBoardChange(int softKeybardHeight, boolean visible);
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/daguaio_o/article/details/47127993