先寫一個類
public class SoftKeyBoardListener {
private ViewrootView;//activity的根視圖
? ? int rootViewVisibleHeight;//紀(jì)錄根視圖的顯示高度
? ? private OnSoftKeyBoardChangeListeneronSoftKeyBoardChangeListener;
public SoftKeyBoardListener(Activity activity) {
//獲取activity的根視圖
? ? ? ? rootView = activity.getWindow().getDecorView();
//監(jiān)聽視圖樹中全局布局發(fā)生改變或者視圖樹中的某個視圖的可視狀態(tài)發(fā)生改變
? ? ? ? rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
? ? ? ? ? ? public void onGlobalLayout() {
//獲取當(dāng)前根視圖在屏幕上顯示的大小
? ? ? ? ? ? ? ? Rectr =new Rect();
rootView.getWindowVisibleDisplayFrame(r);
int visibleHeight =r.height();
System.out.println(""+visibleHeight);
if (rootViewVisibleHeight ==0) {
rootViewVisibleHeight =visibleHeight;
return;
}
//根視圖顯示高度沒有變化,可以看作軟鍵盤顯示/隱藏狀態(tài)沒有改變
? ? ? ? ? ? ? ? if (rootViewVisibleHeight ==visibleHeight) {
return;
}
//根視圖顯示高度變小超過200,可以看作軟鍵盤顯示了
? ? ? ? ? ? ? ? if (rootViewVisibleHeight -visibleHeight >200) {
if (onSoftKeyBoardChangeListener !=null) {
onSoftKeyBoardChangeListener.keyBoardShow(rootViewVisibleHeight -visibleHeight);
}
rootViewVisibleHeight =visibleHeight;
return;
}
//根視圖顯示高度變大超過200灭贷,可以看作軟鍵盤隱藏了
? ? ? ? ? ? ? ? if (visibleHeight -rootViewVisibleHeight >200) {
if (onSoftKeyBoardChangeListener !=null) {
onSoftKeyBoardChangeListener.keyBoardHide(visibleHeight -rootViewVisibleHeight);
}
rootViewVisibleHeight =visibleHeight;
return;
}
}
});
}
private void setOnSoftKeyBoardChangeListener(OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {
this.onSoftKeyBoardChangeListener = onSoftKeyBoardChangeListener;
}
public interface OnSoftKeyBoardChangeListener {
void keyBoardShow(int height);
void keyBoardHide(int height);
}
public static void setListener(Activity activity, OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {
SoftKeyBoardListenersoftKeyBoardListener =new SoftKeyBoardListener(activity);
softKeyBoardListener.setOnSoftKeyBoardChangeListener(onSoftKeyBoardChangeListener);
}
}
在activity中使用
SoftKeyBoardListener.setListener(ApprovalDocumentActivity.this,new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
@Override
public void keyBoardShow(int height) {
mViewInput.setBackgroundColor(Color.GREEN);
mViewHandwriting.setBackgroundColor(Color.GRAY);
}
@Override
public void keyBoardHide(int height) {
mViewHandwriting.setBackgroundColor(Color.GREEN);
mViewInput.setBackgroundColor(Color.GRAY);
}
});