
项目中有时候需要监听keyboard的显示与隐藏,特此备注,方便使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
public class { private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener; private View rootView; private int viewSize = -1; private boolean isShowing = false; private OnKeyboardListener onKeyboardListener; public (Activity activity){ rootView = activity.getWindow().getDecorView().getRootView(); }
public KeyboardWatcher register(OnKeyboardListener listener){ onKeyboardListener = listener; if(onGlobalLayoutListener == null) { onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { Rect r = new Rect(); rootView.getWindowVisibleDisplayFrame(r); int viewHeight = r.bottom - r.top; if(viewSize < 0){ viewSize = viewHeight; return; } if(viewHeight != viewSize){ if(Math.abs(viewHeight - viewSize) > dpToPx(rootView.getContext(),100)) { if (viewHeight < viewSize && !isShowing) { onKeyboardListener.onShow(viewHeight); isShowing = true; } else if(isShowing){ onKeyboardListener.onHide(); isShowing = false; } } viewSize = viewHeight; } } }; }
rootView.post(new Runnable() { public void run() { viewSize = rootView.getHeight(); rootView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener); } });
return this; }
public void unRegister(){ rootView.getViewTreeObserver().removeGlobalOnLayoutListener(onGlobalLayoutListener); rootView = null; }
public interface OnKeyboardListener{
void onShow(int viewSize);
void onHide();
}
private int dpToPx(Context context,int dp) { return (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics() ); } }
|
1 2 3 4
|
KeyBoardWatcher keyboardWatcher = new KeyboardWatcher() keyboardWatcher.register(this)
|
近期评论