package com.lcjian.library.util;
|
|
|
import android.app.Dialog;
|
import android.content.Context;
|
import androidx.fragment.app.Fragment;
|
import android.view.Gravity;
|
import android.view.View;
|
import android.view.Window;
|
import android.view.WindowManager;
|
|
public class DialogUtils {
|
|
private static final String TAG = DialogUtils.class.getName();
|
|
/**
|
* @param dialog
|
* @param fragment
|
* @param hasStatusBar 该页面是否具有statusBar。有,在不包括状态栏的区域居中;没有,在该整个区域居中。
|
*/
|
public static void setDialogInFragmentsCenter(Dialog dialog, Fragment fragment, final boolean hasStatusBar) {
|
|
// 1、获取Dialog所述的Window,以及LayoutParams(布局参数)
|
final Window dialogWindow = dialog.getWindow();
|
dialogWindow.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
|
final WindowManager.LayoutParams lp = dialogWindow.getAttributes();
|
|
// 2、获取到Fragment所处的View
|
final View fragmentView = fragment.getView();
|
// 3、获取到Dialog的DecorView
|
final View dialogView = dialogWindow.getDecorView();
|
dialogView.setVisibility(View.INVISIBLE);
|
dialogView.post(new Runnable() {
|
@Override
|
public void run() {
|
// 4、获取到Fragment左上角点的距离整个屏幕的距离
|
int[] location = new int[2];
|
fragmentView.getLocationOnScreen(location);
|
int fragmentWidth = fragmentView.getMeasuredWidth();
|
int fragmentHeight = fragmentView.getMeasuredHeight();
|
|
|
// 5、获取到Dialog的宽高
|
int dialogWith = dialogView.getMeasuredWidth();
|
int dialogHeight = dialogView.getMeasuredHeight();
|
|
// 6、获取到标题栏的宽高
|
int mStatusBarHeight = 0;
|
|
if (hasStatusBar) {
|
// 有状态栏,需要去除状态栏的影响。
|
mStatusBarHeight = getStatusBarHeight(fragmentView.getContext());
|
}
|
|
|
// 7、Dialog从左上角开始排
|
dialogWindow.setGravity(Gravity.START | Gravity.TOP);
|
// x = fragment的x + fragment宽度/2 - Dialog宽度/2
|
lp.x = location[0] + fragmentWidth / 2 - dialogWith / 2;
|
// y = fragment的y + fragment高度/2 - Dialog高度/2 - 状态栏高度(Gravity.TOP会自动偏移状态栏的高度)
|
lp.y = location[1] + fragmentHeight / 2 - dialogHeight / 2 - mStatusBarHeight;
|
|
// 8、设置Window的属性
|
dialogWindow.setAttributes(lp);
|
// 9、展示出Dialog
|
dialogView.setVisibility(View.VISIBLE);
|
}
|
});
|
}
|
|
public static int getStatusBarHeight(Context context) {
|
/**
|
* 获取状态栏高度——方法2
|
* */
|
int statusBarHeight = -1;
|
try {
|
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
|
Object object = clazz.newInstance();
|
int height = Integer.parseInt(clazz.getField("status_bar_height")
|
.get(object).toString());
|
statusBarHeight = context.getResources().getDimensionPixelSize(height);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return statusBarHeight;
|
}
|
}
|