Android监听软键盘弹出与隐藏

2017-09-27  本文已影响0人  寻味Android

监听布局的GlobalLayoutListener来实现对软键盘弹出与隐藏的监听,先上代码:

public   class  SoftKeyBoardUtil   implements   ViewTreeObserver.OnGlobalLayoutListener {

private   final  ActivitymAct;

private   SoftKeyBoardListener   mListener;

private   View   mChildOfContent;

private   int  usableHeightPrevious;

public  SoftKeyBoardUtil(Activity act){

this.mAct=act;

}

/**

* 软件盘监听

*@paramlistener

*/

public    void    setListener(SoftKeyBoardListener    listener){

this.mListener=listener;

}

/**

* 监听GlobalLayoutListener

*/

public  void    addGlobalLayoutListener(){

mChildOfContent=((ViewGroup)mAct.findViewById(android.R.id.content)).getChildAt(0);

mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(this);

}

/**

* 移除GlobalLayoutListener

*/

public void   removeGlobalLayoutListener(){

mChildOfContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);

}

/**

* 软键盘展示与隐藏逻辑判断

*/

@Override

public void   onGlobalLayout() {

int  usableHeightNow = computeUsableHeight();

if(usableHeightNow !=usableHeightPrevious) {

usableHeightPrevious=usableHeightNow;

int  usableHeightSansKeyboard =mChildOfContent.getRootView().getHeight();

int   heightDifference = usableHeightSansKeyboard - usableHeightNow;

//判断软键盘是否显示逻辑,可以根据具体情况修改

boolean    isKeyBoardShow=heightDifference > (usableHeightSansKeyboard/4);

if(mListener!=null){

mListener.OnSoftKeyboardStateChangedListener(isKeyBoardShow,usableHeightNow);

}

}

}

private   int   computeUsableHeight() {

Rect  rect =new   Rect();

mChildOfContent.getWindowVisibleDisplayFrame(rect);

// rect.top其实是状态栏的高度,如果是全屏主题,直接 return rect.bottom就可以了

return(rect.bottom- rect.top);

}

/**

* 软键盘监听接口

*/

public    static    interface    SoftKeyBoardListener{

void   OnSoftKeyboardStateChangedListener(booleanisKeyBoardShow, intkeyboardHeight);

}

通过mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(this)监听mChildOfContent的布局变化,核心代码是onGlobalLayout()、computeUsableHeight()方法,computeUsableHeight()通过view的getWindowVisibleDisplayFrame(rect)获取view的可见视图区,通常软键盘的弹出隐藏,mChildOfContent的可视区会变化,通过这个computeUsableHeight()获取可视区得高度,然后在onGlobalLayout()方法里处理软键盘是否显示逻辑;boolean   isKeyBoardShow=heightDifference > (usableHeightSansKeyboard/4)这个判断逻辑可以根据情况自己修改。

上一篇下一篇

猜你喜欢

热点阅读