JKBaseLib/BaseLibrary/src/main/java/com/tfq/library/utils/DialogUtils.java

89 lines
3.0 KiB
Java
Raw Normal View History

2025-06-30 13:49:41 +08:00
package com.tfq.library.utils;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import com.tfq.library.R;
/**
* 对话框工具类
*/
public class DialogUtils {
/**
* 为对话框设置模糊背景
* @param dialog 要设置的对话框
* @return 返回添加的模糊背景视图用于后续移除
*/
public static View setBlurBackground(@NonNull Dialog dialog) {
if (dialog.getOwnerActivity() == null) {
return null;
}
// 获取根视图
ViewGroup rootView = (ViewGroup) dialog.getOwnerActivity().getWindow().getDecorView();
// 加载模糊背景
View blurContainer = LayoutInflater.from(dialog.getContext())
.inflate(R.layout.blur_background, rootView, false);
rootView.addView(blurContainer);
// 创建圆角背景
if (dialog.getWindow() != null) {
// 创建圆角矩形
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
// 使用colors.xml中定义的颜色
// int backgroundColor = ContextCompat.getColor(dialog.getContext(), Color.parseColor("#FFFFFFFF"));
int backgroundColor = Color.parseColor("#FFFFFFFF");
shape.setColor(backgroundColor);
shape.setCornerRadius(25f); // 设置圆角半径
// 应用到对话框窗口
dialog.getWindow().setBackgroundDrawable(shape);
// 确保窗口外部是透明的
dialog.getWindow().setDimAmount(0.5f);
}
// 设置对话框消失监听,自动移除模糊背景
dialog.setOnDismissListener(dialogInterface -> rootView.removeView(blurContainer));
return blurContainer;
}
/**
* 检查当前是否处于暗黑模式
* @param context 上下文
* @return 是否为暗黑模式
*/
private static boolean isDarkModeEnabled(Context context) {
int nightModeFlags = context.getResources().getConfiguration().uiMode &
Configuration.UI_MODE_NIGHT_MASK;
return nightModeFlags == Configuration.UI_MODE_NIGHT_YES;
}
/**
* 移除模糊背景
* @param dialog 对话框
* @param blurView 之前添加的模糊背景视图
*/
public static void removeBlurBackground(@NonNull Dialog dialog, View blurView) {
if (dialog.getOwnerActivity() != null && blurView != null) {
ViewGroup rootView = (ViewGroup) dialog.getOwnerActivity().getWindow().getDecorView();
rootView.removeView(blurView);
}
}
}