在我們調用軟鍵盤的時候需要EditText
在軟鍵盤之上一起彈出,正常情況下我們都會在AndroidManifest.xml
中設置android:windowSoftInputMode="stateHidden|adjustResize"
屬性已達到此效果,但是當我們的佈局中有ToolBar
存在的時候我們會發現這個屬性失效了,這個時候可能有些人會首先想到android:fitsSystemWindows="true"
屬性,但是當我們在根佈局中設置此屬性的時候,會發現ToolBar
被拉長了。這裏給大家介紹一個非常不錯的工具類:
/**
* Created by xiaolong on 2017/8/2.
*/
public class AndroidBug5497Workaround {
public static void assistActivity(View content) {
new AndroidBug5497Workaround(content);
}
private View mChildOfContent;
private int usableHeightPrevious;
private ViewGroup.LayoutParams frameLayoutParams;
private AndroidBug5497Workaround(View content) {
if (content != null) {
mChildOfContent = content;
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
frameLayoutParams = mChildOfContent.getLayoutParams();
}
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
//如果兩次高度不一致
// 將計算的可視高度設置成視圖的高度
frameLayoutParams.height = usableHeightNow;
mChildOfContent.requestLayout();//請求重新佈局
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
//計算視圖可視高度
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
return (r.bottom);
}
}
在我們的Activity中調用此類,我們便可以解決上述問題:
AndroidBug5497Workaround.assistActivity(findViewById(android.R.id.content));
這個問題是我在做項目中遇到的問題,試過很多種方法總感覺不是太盡人意,查了好多資料發現了這個方法,記錄下,以備以後用到,哈哈!