android透明狀態列與開源庫SystemBarTint的使用
阿新 • • 發佈:2019-02-10
透明狀態列需要在android4.4及以上版本支援
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//判斷當前系統版本是否是4.4及以上版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//透明狀態列
getWindow().addFlags (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明導航欄
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
這樣就出效果了,但是執行後會發現activity裡的view向上移動了,此時只需要在佈局檔案中加入
android:fitsSystemWindows="true"
android:clipToPadding="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="@color/colorPrimary"
android:fitsSystemWindows="true"
android:clipToPadding ="true"
>
SystemBarTint 是Github 上的一個開源專案,其使用起來也很簡單
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//判斷當前系統版本是否是4.4及以上版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//透明狀態列
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明導航欄
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//例項化一個SystemBarTintManager物件
SystemBarTintManager tintManager = new SystemBarTintManager(this);
//設定狀態列的顏色
tintManager.setStatusBarTintColor(getColor(R.color.colorAccent));
//啟用
tintManager.setStatusBarTintEnabled(true);
}
}
這樣便可便捷的更改狀態列的顏色了