??????小菜前些日子整理了兩次小小的沉浸式狀態(tài)欄的總結:Android 沉浸式狀態(tài)欄的多種樣式 和 Android 沉浸式狀態(tài)欄以及偽沉浸式狀態(tài)欄。今天小菜再稍稍補充一點,Java/Kotlin 代碼中設置 LayerDrawable 方式實現(xiàn)沉浸式狀態(tài)欄。
??????LayerDrawable 為圖層疊加,對應 xml 中的 layer-list 層次化方式展示 Drawable,小菜借用這種方式實現(xiàn)與以前一樣的含有圖片的沉浸式狀態(tài)欄樣式。
?????? GitHub Demo

小菜的測試步驟如下:
- 繪制最底層背景色,且設置了一個小圓角,方便區(qū)分布局中的背景色;
val radius0 = 10
val outerR = floatArrayOf(radius0.toFloat(), radius0.toFloat(), radius0.toFloat(), radius0.toFloat(), radius0.toFloat(), radius0.toFloat(), radius0.toFloat(), radius0.toFloat())
val roundRectShape0 = RoundRectShape(outerR, null, null)
val shapeDrawableBg = ShapeDrawable()
shapeDrawableBg.setPadding(0, 0, 0, 0)
shapeDrawableBg.setShape(roundRectShape0)
shapeDrawableBg.getPaint().setStyle(Paint.Style.FILL)
shapeDrawableBg.getPaint().setColor(-0x444445)
- 設置 LayerDrawable 圖層,底層為上面繪制的特定矩形顏色框,上一層為一張圖片,可用網(wǎng)絡下載或本地圖片;
// 創(chuàng)建資源對象
val resources = resources
// 創(chuàng)建數(shù)組對象
val layers = arrayOfNulls<Drawable>(2)
layers[0] = shapeDrawableBg
layers[1] = resources.getDrawable(R.drawable.icon_bg)
- 在 Toolbar 或其他布局位置設置背景 background;
// 設置背景
toolbar.background = layerDrawable
test_lay.background = layerDrawable

Tips: 圖層的疊加在 layers 中,圖層越往上,添加到 layers[] 數(shù)組中數(shù)組下標越大。
來源: 阿策小和尚