這個特性是andorid4.4支持的,最少要api19纔可以使用。下面介紹一下使用的方法,非常得簡單:
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //透明狀態欄
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
- //透明導航欄
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
- }
- }
- //透明狀態欄
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
- //透明導航欄
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
只要加入這兩行代碼,就可以實現沉浸式通知欄了。效果如圖:
給大家看看這個界面的佈局:
- <LinearLayout 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"
- tools:context=".MainActivity">
- <TextView
- android:layout_width="match_parent"
- android:layout_height="100dp"
- android:background="#009959" />
- <Button
- android:layout_width="100dp"
- android:layout_height="50dp"
- android:background="#ff669d"/>
- </LinearLayout>
是一個垂直的流佈局,但這樣,其實還是有問題的,我在textView裏面加一些文字,就是綠色的那一塊,大家看一下效果:
大家看到了吧,文字和狀態欄重疊在一起了,這肯定是不行的,此時需要添加下面的代碼:
- android:fitsSystemWindows="true"
- android:clipToPadding="true"
- <LinearLayout 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:fitsSystemWindows="true"
- android:clipToPadding="true"
- android:background="#ffffff"
- android:orientation="vertical"
- tools:context=".MainActivity">
- <TextView
- android:layout_width="match_parent"
- android:layout_height="100dp"
- android:background="#009959" />
- <Button
- android:layout_width="100dp"
- android:layout_height="50dp"
- android:background="#ff669d"/>
- </LinearLayout>
大家看紅色的那部分,加入那兩行以後,界面仍然會是沉浸式的,但狀態欄那部分,就不會再重疊了,像加了padding一樣,如下圖:
大家看圖,綠色的textView和紅色的一個button都被下移了,狀態欄是白色的,是背景linearLayout的顏色。很明顯,這也不是我們想要的,我們希望狀態欄和我們放在頂部的控件是同一個顏色,同時,控件內容也不和狀態欄重複,其實,只要把那兩行代碼放到我們頂部的控件就可以了。代碼如下:
- <LinearLayout 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"
- tools:context=".MainActivity">
- <TextView
- android:fitsSystemWindows="true"
- android:clipToPadding="true"
- android:layout_width="match_parent"
- android:layout_height="100dp"
- android:background="#009959"
- android:text="你好,請問你有男朋友嗎"/>
- <Button
- android:layout_width="100dp"
- android:layout_height="50dp"
- android:background="#ff669d"/>
- </LinearLayout>
這就是我們想要的了。