当遇到有虚拟导航按键的时候,我们的沉浸式有时候虚拟导航键有时候也会跟着变色,怎么办呢?
首先看下stytle:
<style name = "ColorTranslucentTheme">parent="AppTheme">
<item name="android:windowTranslucentStatus">false</item>
<!--有的手机有虚拟按键,所以要把windowTranslucentNavigation设置成false,不然会一起变色-->
<item name="android:windowTranslucentNavigation">false</item>
<item name="android:statusBarColor">@android:color/transparent</item>
然后看看在代码里面进行如下判断:
setSupportActionBar(mToolBar);
initSystemBar(this, mToolBar);
public static void initSystemBar(Activity activity, Toolbar mToolbar) {
compat6(activity);
initToolBar(activity,mToolbar);
}
/**
* 如果布局文件里面没添加android:fitsSystemWindows="true"的话,就需要调用该方法
* 该方法是让toolbar加上statubar高度,然后顶上去
* @param activity
* @param toolbar
*/
private static void initToolBar(Activity activity,Toolbar toolbar) {
int mStatuBarHeight = ConstantUtils.getStatusBarHeight(activity);
// int mToolBarHeight = (int) (getResources().getDimension(R.dimen.home_toolbar_hei) + mStatuBarHeight);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ViewGroup.LayoutParams param4 = toolbar.getLayoutParams();
param4.height = param4.height+mStatuBarHeight;
toolbar.setLayoutParams(param4);
toolbar.setPadding(0, mStatuBarHeight, 0, 0);
}
}
public static void compat6(Activity activity)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//透明状态栏
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && ConstantUtils.getNavigationBarHeight(activity) == 0) {
Window window = activity.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);
}
}
}
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/**
* 获取虚拟按键栏高度
* @param context
* @return
*/
public static int getNavigationBarHeight(Context context) {
int result = 0;
if (hasNavBar(context)) {
Resources res = context.getResources();
int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
}
return result;
}
这边需要注意的是,如果你在有toolbar布局的xml文件父布局下写有android:fitsSystemWindows="true"的话,那么就不需要执行initToolBar(activity,mToolbar)方法