Android監(jiān)聽軟鍵盤彈出與隱藏

監(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ù)情況自己修改。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容