Android 沉浸式狀態欄,狀態欄顏色透明

這一特性,需要在 Android 4.4 以上版本中才能使用。

第一種方法,通過XML配置:

首先在 styles.xml 文件中添加一個主題:

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

然後在 AndroidManifest.xml 文件中配置

android:theme="@style/AppTheme"
添加在 application 標籤中,則整個 app 都是沉浸式狀態欄。

添加在 activity 標籤中,則是在某個 activity 中應用沉浸式狀態欄,其餘 activity 不受影響。

第二種方法,在Java代碼中配置:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明狀態欄
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明導航欄
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

    }

}
到這裏已經是沉浸式狀態欄了,但是在實際使用時會發現一個問題,狀態欄不佔空間了,界面最頂端內容會與狀態欄重疊,如下

圖:


所以這裏還需要再做一些處理,在當前界面佈局的最外層 layout 中添加

android:clipToPadding="true"
android:fitsSystemWindows="true"
實際應用如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff8532"
    android:clipToPadding="true"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="liuwan1992"
        android:textColor="#ffffff"
        android:textSize="16sp" />

</LinearLayout>
修改後效果如下:



上面的例子中是對 layout 設置的背景色,如果改成對 TextView 設置呢

很明顯,又出問題了,狀態欄並沒有與 TextView 保持相同顏色,而是與 layout 一樣默認成了白色背景。

那麼,我們將要添加的兩行代碼加入 TextView 中看看效果

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ff8532"
        android:clipToPadding="true"
        android:fitsSystemWindows="true"
        android:text="liuwan1992"
        android:textColor="#ffffff"
        android:textSize="16sp" />

</LinearLayout>

可以看到又達到了我們需要的效果,這裏總結一下,我們在實際開發中,界面的背景顏色可能會另有設置,如果與界面背景保持一

致可能不是我們想要的效果,所以我們一般對界面佈局中最頂端的一個控件做處理。

發佈了44 篇原創文章 · 獲贊 1386 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章