轉自:http://blog.csdn.net/zuiwuyuan/article/details/50100093
Android 使用SystemBarTint設置狀態欄顏色
做項目時,發現APP的狀態欄是系統默認的顏色,突然想到,爲啥別的APP是自己設置的顏色(和APP本身很相搭),於是也想給自己的APP設置系統狀態欄的顏色,更加美美噠。。。
搜了下,發現原來設置狀態欄居然有個很高大上的名字(聽不懂的都是高大上)——沉浸式狀態欄,Android4.4以後開始支持沉浸式狀態欄, 繼續搜索,發現,有一個很簡單的開源項目——SystemBarTint,可以很完美的支持沉浸式狀態欄。
SystemBarTint地址: https://github.com/hexiaochun/SystemBarTint
下面,簡單演示下如何使用該庫,首先,先看下效果,有圖纔有真相:
1. 引入類庫
使用Android Studio,直接在build.gradle文件中引入庫:
-
dependencies {
-
compile 'com.readystatesoftware.systembartint:systembartint:1.0.3'
-
}
2. 在Activity中添加方法:
-
-
-
-
private void applyKitKatTranslucency() {
-
-
-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
-
setTranslucentStatus(true);
-
SystemBarTintManager mTintManager = new SystemBarTintManager(this);
-
mTintManager.setStatusBarTintEnabled(true);
-
-
mTintManager.setStatusBarTintResource(R.color.colorTop);
-
}
-
-
}
-
-
@TargetApi(19)
-
private void setTranslucentStatus(boolean on) {
-
Window win = getWindow();
-
WindowManager.LayoutParams winParams = win.getAttributes();
-
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
-
if (on) {
-
winParams.flags |= bits;
-
} else {
-
winParams.flags &= ~bits;
-
}
-
win.setAttributes(winParams);
-
}
然後, 在OnCreate()方法中調用applyKitKatTranslucency方法:
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main);
-
-
applyKitKatTranslucency();
-
}
3. 在style.xml中,添加系統的樣式:
-
-
<style name="no_title" parent="@android:style/Theme.Light.NoTitleBar">
-
-
-
<item name="android:fitsSystemWindows">true</item>
-
<item name="android:clipToPadding">false</item>
-
</style>
當然了,別忘了在AndroidManifest.xml進行配置主題:
-
<application
-
android:name=".activity.base.MyApp"
-
android:allowBackup="true"
-
android:icon="@drawable/ic_launcher"
-
android:label="@string/app_name"
-
android:persistent="true"
-
android:theme="@style/no_title">
-
</application>
注: 這個是必要的,如果不添加,會造成一些頁面的變形。
綜上, 便可以在4.4以上的系統中方便的設置狀態欄顏色,有木有感覺你的APP變得更好看了呢!