監(jiān)聽布局的GlobalLayoutListener來實現(xiàn)對軟鍵盤彈出與隱藏的監(jiān)聽,先上代碼:
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;
}
/**
* 軟件盤監(jiān)聽
*@paramlistener
*/
public ? ?void ? ?setListener(SoftKeyBoardListener ? ?listener){
this.mListener=listener;
}
/**
* 監(jiān)聽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;
//判斷軟鍵盤是否顯示邏輯,可以根據(jù)具體情況修改
boolean ? ?isKeyBoardShow=heightDifference > (usableHeightSansKeyboard/4);
if(mListener!=null){
mListener.OnSoftKeyboardStateChangedListener(isKeyBoardShow,usableHeightNow);
}
}
}
private ? int ? computeUsableHeight() {
Rect ?rect =new ? Rect();
mChildOfContent.getWindowVisibleDisplayFrame(rect);
// rect.top其實是狀態(tài)欄的高度,如果是全屏主題,直接 return rect.bottom就可以了
return(rect.bottom- rect.top);
}
/**
* 軟鍵盤監(jiān)聽接口
*/
public ? ?static ? ?interface ? ?SoftKeyBoardListener{
void ? OnSoftKeyboardStateChangedListener(booleanisKeyBoardShow, intkeyboardHeight);
}
通過mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(this)監(jiān)聽mChildOfContent的布局變化,核心代碼是onGlobalLayout()、computeUsableHeight()方法,computeUsableHeight()通過view的getWindowVisibleDisplayFrame(rect)獲取view的可見視圖區(qū),通常軟鍵盤的彈出隱藏,mChildOfContent的可視區(qū)會變化,通過這個computeUsableHeight()獲取可視區(qū)得高度,然后在onGlobalLayout()方法里處理軟鍵盤是否顯示邏輯;boolean ? isKeyBoardShow=heightDifference > (usableHeightSansKeyboard/4)這個判斷邏輯可以根據(jù)情況自己修改。