我有三個片段。我只想在一個片段上應用透明狀態欄。為此,我setOnItemSelectedListener在底部導航欄的方法上呼叫以下隱藏方法。還添加了我現在得到的影像
private fun hideStatusBar() {
window.statusBarColor = ContextCompat.getColor(this@SuperActivity, R.color.transparent)
WindowCompat.setDecorFitsSystemWindows(window, false)
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets ->
val insets = windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars())
view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
leftMargin = insets.left
rightMargin = insets.right
bottomMargin = insets.bottom
}
WindowInsetsCompat.CONSUMED
}
}
private fun showStatusBar() {
window.statusBarColor = ContextCompat.getColor(this@SuperActivity, R.color.transparent)
WindowCompat.setDecorFitsSystemWindows(window, true)
}
我在片段呼叫 hide 方法上獲得了適當的行為。

但是當我點擊另一個片段(需要顯示狀態欄的片段)時,我得到以下行為:

uj5u.com熱心網友回復:
底部邊距默認為0(或根布局“ binding.root”中的指定值)
因此,您需要再次重置底部邊距;如果已經是0;然后你可以:
private fun showStatusBar() {
window.statusBarColor = ContextCompat.getColor(this@SuperActivity, R.color.transparent)
WindowCompat.setDecorFitsSystemWindows(window, true)
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets ->
val insets = windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars())
view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
bottomMargin = 0 // reset the margin
}
WindowInsetsCompat.CONSUMED
}
}
}
或者如果是別的東西;然后您需要將其從 dp 轉換為像素并將其設定為bottomMargin
如果您在 binding.root 中有一些指定的邊距值,則同樣適用;但我認為你沒有,因為問題只出現在底部。
更新:
方法 setOnApplyWindowInsetsListener 不會在 showStatusBar 方法中呼叫。因為在這種情況下,Window Insets 沒有改變。因為,我們在 hideStatusBar 方法中添加了邊距,所以您在導航欄下方看到的這個空間來自 hideStatusBar 方法。
雖然應該觸發監聽器,但是可以直接更新root:
binding.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
bottomMargin = 0
}
但是請注意,setDecorFitsSystemWindows更新可能需要一些時間,因此updateLayoutParams不會產生影響,因此,您可能需要一點延遲:
Handler(Looper.getMainLooper()).postDelayed( {
binding.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
bottomMargin = 0
}
}, 0.1.toLong())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/355663.html
