首先这需求不怎么常见,一般用于单纯的弹框做需求太复杂。就好像业务是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))
}
如果你还遇到其他问题,欢迎私信或者评论交流。
网友评论