美文网首页待修改-精通安卓
关于如何实现android状态栏沉淀式效果

关于如何实现android状态栏沉淀式效果

作者: 的一幕 | 来源:发表于2016-07-20 14:51 被阅读337次

第一步:

首先得让你的activity的布局文件的根布局有android:fitsSystemWindows="true"该属性,它指定了状态栏占有一定的位子.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical" 
    android:fitsSystemWindows="true">

第二步:

在你的activity的onCreate方法中调用该方法:

@TargetApi(19)
private void initWindow() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
        View mStatusBarTintView = new View(this);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, getStatusBarHeight());
        params.gravity = Gravity.TOP;
        mStatusBarTintView.setLayoutParams(params);   
        mStatusBarTintView.setBackgroundColor(getResources().getColor(DEFAULT_TINT_COLOR));
        mStatusBarTintView.setVisibility(View.VISIBLE);
        decorView.addView(mStatusBarTintView);
    }
}
protected int getStatusBarHeight(){  
    Class<?> c = null;
    Object obj = null;
    Field field = null;
    int x = 0, sbar = 38;//默认为38,貌似大部分是这样的
    try {
          c = Class.forName("com.android.internal.R$dimen");
          obj = c.newInstance();
          field = c.getField("status_bar_height");
          x = Integer.parseInt(field.get(obj).toString());
          sbar = getResources().getDimensionPixelSize(x);
     } catch (Exception e1) {
          e1.printStackTrace();
     }
     return sbar;
}

这里获取状态栏的获取就不说了,上一篇文章已经说过了关于如何获取android状态栏高度,上面的DEFAULT_TINT_COLOR就是你要指定的状态栏颜色值,我这里设置的颜色值跟toolbar的颜色一样。

相关文章

网友评论

本文标题:关于如何实现android状态栏沉淀式效果

本文链接:https://www.haomeiwen.com/subject/oqmvjttx.html