在主題(theme)中設置windowTranslucentStatus爲true將填充頂部的狀態欄區域。(有虛擬按鍵的設備上)設置windowTranslucentNavigation爲true將填充底部導航欄的區域。這兩種樣式默認會把應用的內容放到系統欄下面。java
若是僅僅想擴展背景樣式到系統欄下,設置fitsSystemWindows爲true會增長 視圖 的Padding值讓你的佈局恢復正常大小,而且能夠把視圖的背景擴大。android
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="android:Theme.Holo.Light"> <item name="android:windowBackground">@color/green</item> <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> <item name="android:fitsSystemWindows">true</item> <item name="android:actionBarStyle">@style/ActionBar.Solid.GreenStyle</item> </style> <style name="ActionBar.Solid.GreenStyle" parent="@android:style/Widget.Holo.Light.ActionBar.Solid"> <item name="android:background">@color/green_accent</item> </style> </resources>
將上面的主題應用到Application 或Activity 上, activity的背景色就會填充狀態欄 (和底部導航欄,有的話)。app
@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); View root = findViewById(R.id.layout_activity_main); root.setFitsSystemWindows(true); ... }
activity_main.xml中 背景色設置爲藍色,因此狀態欄和導航欄都是藍色背景(本來是黑色的): ide
好比最上面綠色的搜索框 'topBar',其layout 以下:
佈局
... <LinearLayout android:fitsSystemWindows="true" android:id="@+id/top_bar" android:layout_width="match_parent" android:layout_height="90dp" android:orientation="horizontal" android:background="@android:color/holo_green_light" android:gravity="center_vertical" android:padding="12dp"> <TextView .../> ... </LinearLayout> ...
這樣設置之後就會有以下的效果:spa
topBar 原來的padding 所有變爲0, 而後上面的padding從新設置爲 狀態欄的高度,下面的padding從新設置爲導航欄的高度,這樣最後剩餘的空間來存放topBar中原始的content,能夠看出原始的content被擠壓了,由於topBar的高度是不變的,若是設置的太小,content會顯示不全甚至徹底不可見。code
這種效果顯然不可接受, 能夠設置底部導航欄爲透明,這樣topBar背景只擴展至狀態欄。xml
//透明狀態欄 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明導航欄 //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); //非透明導航欄 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); 或者在主題中設置: <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">false</item>
總結:get
以上所指的‘視圖’必須是與statusBar或底部的系統導航欄緊鄰的, it
1,能夠是activity的content view;
2,也能夠是contentView中的某個childView,只要這個view在status bar 下面而且相鄰,這時只有statusBar設置透明;
3,也能夠是底部某事childView, 只要這個view在虛擬導航欄上部而且緊鄰,這時只有虛擬導航欄設置透明