一种沉浸式状态栏的实现方式

版权声明:欢迎转载,评论 https://blog.csdn.net/qq_29645505/article/details/88766370

首先去除顶部自带的标题栏,并且只有在**Android 4.4(API 19)**以上版本才适用:

requestWindowFeature(Window.FEATURE_NO_TITLE);//不显示标题栏
setContentView(R.layout.activity_main2);
if (Build.VERSION.SDK_INT >= 19) {//android 4.4 以上 沉浸式菜单
Window window =getWindow();
window.addFlags(67108864);
}

需要注意的是,用此方法实现沉浸式状态栏效果后,会产生一个bug:如果页面中出现了输入框,弹出软键盘后,输入框将被软键盘覆盖,即使在清单文件中设置了windowSoftInputMode="adjustResize"也无济于事。
好在网上提供了解决此bug的源代码:AndroidBug5497Workaround.java
在Activity后台代码中进行调用该类的 assistActivity(Activity activity) 方法即可解决bug:

AndroidBug5497Workaround.assistActivity(WebActivity.this);

顺便将AndroidBug5497Workaround.java源码贴出:

package com.wunian.util;
import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
public class AndroidBug5497Workaround {
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 > (usableHeightSansKeyboard / 4)) {
// 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);
// return (r.bottom - r.top);
return (r.bottom);
}
}

猜你喜欢

转载自blog.csdn.net/qq_29645505/article/details/88766370