在Android中我們經(jīng)常需要設(shè)置屏幕頂部狀態(tài)欄的主題和應(yīng)用頁面保持同一風(fēng)格蔽午,本文介紹幾種常用的設(shè)置方案:
狀態(tài)欄將顯示為純凈的顏色橘霎,沒有漸變效果
/**
* 狀態(tài)欄相關(guān)工具類
*
*/
public class StatusBarUtils {
//設(shè)置Activity對應(yīng)的頂部狀態(tài)欄的顏色
public static void setWindowStatusBarColor(Activity activity, int colorResId) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(activity.getResources().getColor(colorResId));
}
} catch (Exception e) {
e.printStackTrace();
}
}
//設(shè)置Dialog對應(yīng)的頂部狀態(tài)欄的顏色
public static void setWindowStatusBarColor(Dialog dialog, int colorResId) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = dialog.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(dialog.getContext().getResources().getColor(colorResId));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
通過style來設(shè)置應(yīng)用頂部狀態(tài)欄的顏色
首先給出一張圖:
2
通過上圖鉴逞,我們可以通過設(shè)置不同的屬性來達(dá)到控制不同位置顏色的目的,下面給出使用示例萎羔,修改res/values-19里面的內(nèi)容:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@android:color/holo_blue_bright</item>
<item name="colorPrimaryDark">@android:color/holo_blue_bright</item>
</style>
主要是設(shè)置 colorPrimary滔吠,colorPrimaryDark這兩個(gè)屬性的值來設(shè)置狀態(tài)欄的顏色抵恋,需要注意的是:
1:AndroidManifest.xml文件中的targetSdkVersion必須設(shè)置在 21 以上焕议。
2.parent主題必須是 Theme.AppCompat 開頭,兼容包下的主題弧关,所以必須一用 v7 包盅安。
在頂部標(biāo)題欄設(shè)置屬性值達(dá)到風(fēng)格一致的目的
首先修改res/values-v19文件夾下的styles.xml文件內(nèi)容如下(如果沒有可以新建一個(gè)):
<style name= "AppTheme" parent="@style/BaseAppTheme">
<item name="android:windowTranslucentStatus">true</item>
</style>
然后設(shè)置頂部標(biāo)題控件的兩個(gè)屬性:
android:background="@android:color/holo_blue_bright"
android:fitsSystemWindows="true"
這時(shí)狀態(tài)欄會保持與設(shè)置fitsSystemWindow屬性的控件的背景顏色一致。