最近看到許多app的狀態欄和應用界面融爲一體的效果,與Android原生黑乎乎的狀態欄相比,這種視覺感受非常棒,用戶體驗更好些。此效果稱爲沉浸式,不過有些開發者把它叫做全透明的狀態欄。在此不做過多糾結,個人覺得前者叫法更有逼格些。
沉浸式狀態欄效果是從Android 4.4 系統(API=19)開始加入的,故要實現此效果手機系統得是4.4以上的版本。參考網上其他網友的做法是修改style.xml..主題樣式。個人感覺太過繁瑣,故綜合整理了使用java代碼方式實現沉浸式效果,在Activity的onCreate()方法裏兩個if語句搞定。
public class MainActivity extends Activity{
@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);
}
//5.0 全透明實現
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);// calculateStatusColor(Color.WHITE, (int) alphaValue)
}
}
}
activity_main.xml佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
1,添加了上述的Java和xml佈局文件後,可看到此時的狀態欄是白色的。我們可以爲LinearLayout設置一個背景顏色如綠色:android:background="#0f0"後,效果
2,也可以在activity_main.xml佈局裏添加一張圖片使之沉浸到狀態欄裏,xml代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:background="@mipmap/icon"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
效果:
3,可發現當LinearLayout裏包裹的是一個TextView控件時會出現,textview的文字和狀態欄重疊在一起,解決方法在TextView裏添加android:fitsSystemWindows="true"屬性。
xml佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:background="#cb7aeb"
android:layout_height="60dp">
<TextView
android:text="測試文本測試文本測試文本測試文本測試文本測試文本"
android:fitsSystemWindows="true"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
<ImageView
android:background="@mipmap/icon"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
在TextView控件裏添加android:fitsSystemWindows="true"屬性後: 可以看到此時狀態欄的顏色和FrameLayout設置的背景顏色一致,且textview和狀態欄分隔開來了,符合正常效果
最後大家可以吧此activity寫爲一個BaseActivity,其他Activity繼承BaseActivity即可。