工具類:
public classSoftKeyBoardListener {
privateViewrootView;//activity的根視圖
private introotViewVisibleHeight;//紀錄根視圖的顯示高度
privateOnSoftKeyBoardChangeListeneronSoftKeyBoardChangeListener;
publicSoftKeyBoardListener(Activity activity) {
//獲取activity的根視圖
rootView= activity.getWindow().getDecorView();
//監(jiān)聽視圖樹中全局布局發(fā)生改變或者視圖樹中的某個視圖的可視狀態(tài)發(fā)生改變
rootView.getViewTreeObserver().addOnGlobalLayoutListener(newViewTreeObserver.OnGlobalLayoutListener() {
@Override
public voidonGlobalLayout() {
//獲取當前根視圖在屏幕上顯示的大小
Rect r =newRect();
rootView.getWindowVisibleDisplayFrame(r);
intvisibleHeight = r.height();
if(rootViewVisibleHeight==0) {
rootViewVisibleHeight= visibleHeight;
return;
}
//根視圖顯示高度沒有變化,可以看作軟鍵盤顯示/隱藏狀態(tài)沒有改變
if(rootViewVisibleHeight== visibleHeight) {
return;
}
//根視圖顯示高度變小超過300轨蛤,可以看作軟鍵盤顯示了
if(rootViewVisibleHeight- visibleHeight >200) {
if(onSoftKeyBoardChangeListener!=null) {
onSoftKeyBoardChangeListener.keyBoardShow(rootViewVisibleHeight- visibleHeight);
}
rootViewVisibleHeight= visibleHeight;
return;
}
//根視圖顯示高度變大超過300厅各,可以看作軟鍵盤隱藏了
if(visibleHeight -rootViewVisibleHeight>200) {
if(onSoftKeyBoardChangeListener!=null) {
onSoftKeyBoardChangeListener.keyBoardHide(visibleHeight -rootViewVisibleHeight);
}
rootViewVisibleHeight= visibleHeight;
return;
}
}
});
}
private voidsetOnSoftKeyBoardChangeListener(OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {
this.onSoftKeyBoardChangeListener= onSoftKeyBoardChangeListener;
}
public interfaceOnSoftKeyBoardChangeListener {
voidkeyBoardShow(intheight);
voidkeyBoardHide(intheight);
}
public static voidsetListener(Activity activity,OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {
SoftKeyBoardListener softKeyBoardListener =newSoftKeyBoardListener(activity);
softKeyBoardListener.setOnSoftKeyBoardChangeListener(onSoftKeyBoardChangeListener);
}
public static voidcloseKeybord(EditText mEditText,Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(),0);
mEditText.setFocusable(false);
}
}
使用:
SoftKeyBoardListener.setListener(this,
newSoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
@Override
public voidkeyBoardShow(intheight) {
Log.e("TAG","keyBoardShow: ");
if(setPadding==true) {
scroll.setPadding(0,0,0,height);
scroll.scrollTo(0,0);
}
}
@SuppressLint("WrongConstant")
@Override
public voidkeyBoardHide(intheight) {
scroll.setPadding(0,0,0,0);
scroll.scrollTo(0,0);
}
});