Android開發Activity彈框形式並且狀態欄透明

首先這需求不怎麼常見,一般用於單純的彈框做需求太複雜。就好像業務是Activity的,但是UI是彈框的。
下面我們一步步來:

一、先將Activity弄成彈框的樣式

 <style name="dialog_activity" parent="Theme.AppCompat.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="o_mr1">shortEdges</item>
</style>

注意:parent="Theme.AppCompat.Dialog",它背景纔有彈框的樣式

"android:windowLayoutInDisplayCutoutMode":因爲我的需求是狀態欄透明,即內容頂到狀態欄下面,這個是適配Android11以上的手機

二、狀態欄透明(內容頂到狀態下面)

在onCreate裏面寫

public static void setTranslucentStatus(Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // 5.x開始需要把顏色設置透明,否則導航欄會呈現系統默認的淺灰色
        Window window = activity.getWindow();
        View decorView = window.getDecorView();
        // 兩個 flag 要結合使用,表示讓應用的主體內容佔用系統狀態欄的空間
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(option);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
        // 導航欄顏色也可以正常設置
        // window.setNavigationBarColor(Color.TRANSPARENT);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window window = activity.getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        attributes.flags |= flagTranslucentStatus;
        // int flagTranslucentNavigation =
        // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        // attributes.flags |= flagTranslucentNavigation;
        window.setAttributes(attributes);
    }
}

三、內容佔滿屏幕的設置

設置爲上面,你可能會發現內容沒佔滿屏幕,就算你佈局寫了佔滿屏幕,它也是擠在中間,沒佔滿寬。
需在onCreate裏面做如下配置:

window.run {
        setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        setBackgroundDrawable(getDrawables(R.color.transparent))
    }

如果你還遇到其他問題,歡迎私信或者評論交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章