剛開始的狀態欄,我們設定的布局是從狀態欄下開始繪制的:

代碼設定狀態欄全透明,我們設定的布局內容從狀態欄開始繪制了:
class UITool {
companion object {
/**
* make status bar full transparent
*/
fun fullTransparentStatusBar(activity: Activity) {
val window = activity.window
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//SDK 21,Android 5.0
window.clearFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
)
window.decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = Color.TRANSPARENT
// window.decorView.findViewById<View>(android.R.id.content).fitsSystemWindows = true
// window.navigationBarColor = Color.TRANSPARENT
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//SDK 19,Android 4.4, not support full transparent
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
}
}
效果如下:

如果不想把內容頂到狀態欄,可以在上面代碼基礎上,在布局檔案的根布局添加【android:fitsSystemWindows=“true”】
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/mClickButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
效果如下,這里狀態欄背景色就跟布局檔案中背景色一致了,內容卻移到狀態欄下面了:

當然也可以在上面那個方法里添加下面代碼,也就是找到我們的根布局并設定【fitsSystemWindows】true:
window.decorView.findViewById<FrameLayout>(android.R.id.content).getChildAt(0).fitsSystemWindows = true
現在看到的狀態欄和背景色都是白色,這是因為內容部分背景色主題默認是白色的,改變內容背景色就可以了【android:background="#ff0000"】,當然背景也可以是圖片【android:background="@drawable/ic_launcher_background"】
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/ic_launcher_background"
tools:context=".MainActivity">
<Button
android:id="@+id/mClickButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
效果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/287174.html
標籤:其他
