最近在给项目添加沉浸式状态栏时遇到了一个很奇葩的问题,在Android4.4以上系统底部聊天及评论框不能被系统输入法顶上去。
在你的Activity的oncreate()方法里调用AndroidBug5497Workaround.assistActivity(this);即可。注意:在setContentView(R.layout.xxx)之后调用。
原因是因为设置状态栏透明后没有设置android:fitsSystemWindows="true"这个属性。我的解决办法是使用AndroidBug5497Workaround 类动态计算布局的高度。这个方法原始代码在华为等手机上存在高度计算不准确的兼容性问题。我在源码的基础上做了一些修改,目前在华为,小米,三星等手机上测试均正常,修改后的代码如下。
public class AndroidBug5497Workaround {
// For more information, see https://code.google.com/p/android/issues/detail?id=5497
// To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
public static void assistActivity(Activity activity) {
new AndroidBug5497Workaround(activity);
}
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private AndroidBug5497Workaround(Activity activity) {
FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > 0) {
// keyboard probably just became visible
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
} else {
// keyboard probably just became hidden
frameLayoutParams.height = usableHeightSansKeyboard;
}
mChildOfContent.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
if (r.top == 0) {
r.top = AppBarView.getStatusBarHeight();//状态栏目的高度
}
return r.bottom;
}
}