Android 沉浸式状态栏键盘不受挤压布局解决方案

上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
/*| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION*/);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
/*| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION*/
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
// window.setNavigationBarColor(Color.TRANSPARENT);
LinearLayout linear_bar = (LinearLayout) findViewById(R.id.status_bar_ll);
linear_bar.setVisibility(View.VISIBLE);
//获取到状态栏的高度
int statusHeight = SystemUtil.getStatusBarHeight(this);
//动态的设置隐藏布局的高度
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) linear_bar.getLayoutParams();
params.height = statusHeight;
linear_bar.setLayoutParams(params);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 通过反射的方式获取状态栏高度
* @return
*/
public static int getStatusBarHeight(Context context) {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
return context.getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}

其中:linear_bar 为布局里面标题栏上面1dp大小占位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/base_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<LinearLayout
android:id="@+id/status_bar_ll"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="@color/main_theme_color"
android:orientation="vertical"
android:visibility="gone"/>

<LinearLayout
android:id="@+id/layout_head"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="@color/main_theme_color"
android:orientation="horizontal">
...

以上就实现了Android 沉浸式状态栏。

但如果你Activity底部有输入框,需要弹出键盘,上述方式会导致布局不受挤压键盘,直接遮挡住输入框,解决方案很简单,即在布局文件最开头加入:

1
android:fitsSystemWindows="true"