關于如何實現(xiàn)android狀態(tài)欄沉淀式效果

第一步:

首先得讓你的activity的布局文件的根布局有android:fitsSystemWindows="true"該屬性,它指定了狀態(tài)欄占有一定的位子.

<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方法中調(diào)用該方法:

@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;
}

這里獲取狀態(tài)欄的獲取就不說了,上一篇文章已經(jīng)說過了關于如何獲取android狀態(tài)欄高度,上面的DEFAULT_TINT_COLOR就是你要指定的狀態(tài)欄顏色值,我這里設置的顏色值跟toolbar的顏色一樣。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容