05.30 android軟鍵盤狀態監聽最穩的方法,屬性動畫手動調整佈局

最近忙於自媒體事業不能自拔,已經很久沒有寫技術博客了。之所以寫是因為這個非常的重要,也非常的好用(軟鍵盤衝突的問題總是非常的讓安卓程序員頭疼)。先上一張完美的效果圖。

android軟鍵盤狀態監聽最穩的方法,屬性動畫手動調整佈局

 //監聽鍵盤展開 、收起
private void listenerKeyBoard() {
getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//當頁面佈局發生變化的時候調用
YetuLog.e("onLayoutChange", "onLayoutChange: " + "調用");
//因為addOnGlobalLayoutListener是在頁面加載完成後才調用,所以當前獲取的View參數都是真實有效
int[] location = new int[2];
rlMiddle.getLocationOnScreen(location);
rl_height = location[1];
setViewHeight();
}
});
}
private boolean isSoftShowing() {
//獲取當前屏幕內容的高度
int screenHeight = getWindow().getDecorView().getHeight();
//獲取View可見區域的bottom
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
return screenHeight - rect.bottom != 0;
}
private void setViewHeight() {
// YetuLog.e("onLayoutChange", "onLayoutChange: " + rl_height);
if (isSoftShowing()) {
//軟鍵盤彈出
// YetuLog.e("onLayoutChange", "onLayoutChange: " + "彈出");
//rl_height==0 頁面已經上移,不再向上移動(這裡是對非軟鍵盤導致的佈局切換變化做一個判斷)
if (rl_height != 0) {
ObjectAnimator translationY = new ObjectAnimator().ofFloat(rlMiddle, "translationY", 0, -layTop.getBottom());
//在這裡0表示當前控件的位置
translationY.setDuration(200);
translationY.start();
}

} else {
//軟鍵盤收起
// YetuLog.e("onLayoutChange", "onLayoutChange: " + "收起");
if (rl_height == 0) {
ObjectAnimator translationY = new ObjectAnimator().ofFloat(rlMiddle, "translationY", -layTop.getBottom(), 0);
translationY.setDuration(200);
translationY.start();
}
}
}
@Override
protected void onResume() {
super.onResume();
//addOnGlobalLayoutListener 判斷頁面是否已經加載完畢
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
/**
* Callback method to be invoked when the global layout state or the visibility of views
* within the view tree changes
*/
@Override
public void onGlobalLayout() {
//判斷是否第一次進入頁面
if (!isLoaded) {
isLoaded = true;
listenerKeyBoard();
}else{
int[] location = new int[2];
rlMiddle.getLocationOnScreen(location);
rl_height = location[1];
// YetuLog.e("onLayoutChange", "onLayoutChange: " + "重新初始化" + rl_height);
setViewHeight();
}
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}

大概講一下邏輯吧。首先是執行onResume方法裡的代碼,這裡面isLoaded是一個標記,只有在第一次進入該頁面的時候,才會調用listenerKeyBoard方法,啟動onLayoutChange監聽。else的情況是在進入下一個頁面,然後再返回有編輯框的時候,直接調用判斷軟鍵盤狀態的方法setViewHeight()同時設置頁面動畫。這其中,lay_top是那個帶有返回鍵的控件,rlMiddle這是那整塊在移動的控件。調用addOnGlobalLayoutListener是為了確認佈局已經加載完成,這樣才能準確的獲取控件寬高之類的參數。其中,判斷軟鍵盤狀態的核心方法是isSoftShowing()。剩下的代碼註釋都有,佈局文件就不貼出來了。

android軟鍵盤狀態監聽最穩的方法,屬性動畫手動調整佈局

上圖是附錄測試log。該套方法主要用於,在頁面沒有ScrollView或者RecyclerView之類的列表或者EditView太高,而其他的控件又太低,沒辦法把底下的這些控件頂起來,只能手動移動控件的時候。之所以使用屬性動畫,沒有直接onlayout(),是考慮到整個佈局的平滑過渡,使用屬性動畫的體驗會更好些。

android軟鍵盤狀態監聽最穩的方法,屬性動畫手動調整佈局


分享到:


相關文章: