Android自5.0以后,应用可以实现类似iOS的状态栏变色功能,类似Android版的知乎。这种实现方式很简单,只需要在style里面指定颜色即可。但是类似Google play的将布局的内容延伸到状态栏就没有那么简单了,如下图,NavigationView已经延伸到了状态栏的下面。
那么如何才能实现这一个效果呢?话不多说,直接上代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
View decorView = window.getDecorView();
decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
return defaultInsets.replaceSystemWindowInsets(
defaultInsets.getSystemWindowInsetLeft(),
0,
defaultInsets.getSystemWindowInsetRight(),
defaultInsets.getSystemWindowInsetBottom());
}
});
ViewCompat.requestApplyInsets(decorView);
//将状态栏设成透明,如不想透明可设置其他颜色
window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
}