android修改状态栏颜色 布局错乱问题解决
转载请注明出处(http://blog.csdn.net/ps1397111/article/details/49929045)
修改装状态栏颜色需要用的的库
SystemBarTintManager开源库
看一看状态栏变色效果
状态栏变色需要的代码,只能在4.4以上的机器上运行,并且必须开启透明主题。
首先是manifest里面activity的theme
android:theme="@android:style/Theme.Translucent.NoTitleBar"
这个目的是让布局透明,并隐藏标题栏。
然后在activity里面需要的代码
//状态栏变色
if (UenUtils.getSDKVersion() > 18) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
winParams.flags |= bits;
win.setAttributes(winParams);
// 创建状态栏的管理实例
SystemBarTintManager tintManager = new SystemBarTintManager(this);
// 激活状态栏设置
tintManager.setStatusBarTintEnabled(true);
// 激活导航栏设置
// tintManager.setNavigationBarTintEnabled(true);
// 设置一个颜色给系统栏
tintManager.setTintColor(Color.parseColor("#BC1E21"));
}
讲一讲在开发过程中遇到的问题,首先是在manifest中theme设置为了android:theme="@android:style/Theme.Translucent"
,但是在模拟器上运行效果没有任何问题,然后在自己的索尼Z3上也没问题,之后在小米note和华为上,发现在手机状态栏和app的title中间是灰色的。之后发现灰色是因为没有设置NoTitleBar属性导致的。之后设置了NoTitleBar,又发现app的title被状态栏挡住了一部分,百思不得其解。最后在网上查了半天解决了问题,在布局中添加一行属性,解决问题。
android:fitsSystemWindows="true"
这个的实质是 4.x 风格的状态栏半透明。它会把状态栏那一块先蒙上一层半透明的灰色(#66000000)遮罩,再和主要试图区域连在一起,扔给你的 activity。故而你的 actionBar 会上挪到屏幕顶部,修正的方法是在布局 xml 的 root 节点里加入:
android:fitsSystemWindows="true"
即可。如果布局比较复杂的话,简单的 fitsSystemWindows 也许就不能应付需求了,若需要手工计算顶栏(statusBar)的高度,送人送到底我还是贴出来吧:
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
对应的底部虚拟按键是 android:windowTranslucentNavigation。
顺便mark一下各种theme
android:theme="@android:style/Theme.Dialog" : Activity显示为对话框模式
android:theme="@android:style/Theme.NoTitleBar" : 不显示应用程序标题栏
android:theme="@android:style/Theme.NoTitleBar.Fullscreen" : 不显示应用程序标题栏,并全屏
android:theme="Theme.Light ": 背景为白色
android:theme="Theme.Light.NoTitleBar" : 白色背景并无标题栏
android:theme="Theme.Light.NoTitleBar.Fullscreen" : 白色背景,无标题栏,全屏
android:theme="Theme.Black" : 背景黑色
android:theme="Theme.Black.NoTitleBar" : 黑色背景并无标题栏
android:theme="Theme.Black.NoTitleBar.Fullscreen" : 黑色背景,无标题栏,全屏
android:theme="Theme.Wallpaper" : 用系统桌面为应用程序背景
android:theme="Theme.Wallpaper.NoTitleBar" : 用系统桌面为应用程序背景,且无标题栏
android:theme="Theme.Wallpaper.NoTitleBar.Fullscreen" : 用系统桌面为应用程序背景,无标题栏,全屏
android:theme="Theme.Translucent : 透明背景
android:theme="Theme.Translucent.NoTitleBar" : 透明背景并无标题
android:theme="Theme.Translucent.NoTitleBar.Fullscreen" : 透明背景并无标题,全屏
android:theme="Theme.Panel ": 面板风格显示
android:theme="Theme.Light.Panel" : 平板风格显示