Android透明状态栏的使用

从Android 4.4 开始,我们可以修改状态栏的颜色。本文主要是总结下修改过程遇到的一些问题。

透明状态栏

values-v19values-v21目录下分别创建style.xml.在style.xml中添加AppBaseTheme:

    <style name="MyBaseTheme"parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowTranslucentStatus">true</item>
    </style>

其中<item name="android:windowTranslucentStatus">true</item>则是将状态栏透明,使我们的布局界面延伸到状态栏。如图:

pic1.png

很明显上面的效果不是我们想要的。除了标题栏顶到了statusBar导致重叠了,而且4.4和5.0+的显示效果也不一样。我们来看下规范的Material Design:

pic4.png

默认的md风格是状态栏应该是20%透明的黑色(#33000000)。
首先解决第一个问题,要想不重叠我可以在布局文件中加上android:fitsSystemWindows="true"或者添加一个和状态栏高度相等的view。我这里用的是第二种方法。实现一个自定义的View StatusBarPlaceHolder:

public class StatusBarPlaceHolder extends RelativeLayout{

    private int statusHeight;

    public StatusBarPlaceHolder(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public StatusBarPlaceHolder(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            statusHeight = getStatusHeight(context);
        }else {
            statusHeight = 0;
        }
    }

    private int getStatusHeight(Context context){
        int result = 0;
        int resultId = context.getResources().getIdentifier("status_bar_height","dimen","android");
        if (resultId > 0){
            result = context.getResources().getDimensionPixelOffset(resultId);
        }
        return result;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = MeasureSpec.makeMeasureSpec(statusHeight,MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, height);
    }
}

添加上面的view到布局文件后运行效果如图:


pic2.png

OK,看起来总算不那么难看了,下面解决第二个问题,让4.4上的状态栏尽量的贴近标准的md样式,这里我用到了一个很好的第三方库Android System Bar Tint

// create our manager instance after the content view is set
SystemBarTintManager manager = new SystemBarTintManager(this);
// enable status bar tint
manager.setStatusBarTintEnabled(true);
// set a custom tint color for all system bars
manager.setStatusBarTintColor(Color.parseColor("#33000000"));

再来看下效果:

pic3.png

差不多就这个样子吧。

遇到的问题

这里在开发中遇到了一个问题,就是在项目中用到了软键盘,在透明了状态栏之后android:windowSoftInputMode="adjustResize"就失去效果了,editText就弹不起来了。我这里用到的解决方案是在布局文件中加入android:fitsSystemWindows="true"使布局文件在状态栏之下。关于这个问题还可以参考其他的解决方案

Tips

  • android:fitsSystemWindows="true"在一个Activity的界面中只能有1个
  • 注意android:fitsSystemWindows="true"添加的位置,不要导致之前设置过的view被顶下来了。
  • 当然api 21以上可以也可以用<item name="statusBarColor">@color/primary_dark</item>来设置状态栏颜色。

参考 :Demo源码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容