Dialog设置window的属性必须在show之后才有效
@Override
public void onStart() {
super.onStart();
//只有dialog show后才能设置window的属性
final Dialog dialog = getDialog();
final Window window = dialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(Color.WHITE));//必须设置Background,否则width即使MATCH_PARENT也不会顶边
final Size size = getScreenSize();
final WindowManager.LayoutParams attributes = window.getAttributes();
attributes.width = (int) (size.getWidth() * 0.8);
window.setAttributes(attributes);
//设置布局
//window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//设置背景为透明
//window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
private Size getScreenSize() {
final WindowManager windowManager = requireActivity().getWindowManager();
Display display;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
Rect rect = metrics.getBounds();
return new Size(rect.width(), rect.height());
} else {
DisplayMetrics metrics = new DisplayMetrics();
display = windowManager.getDefaultDisplay();
display.getMetrics(metrics);
return new Size(metrics.widthPixels, metrics.widthPixels);
}
}
在Activity和Fragment中使用
onThreadDownloadApkProcess是每过500毫秒调用一次。在onThreadDownloadApkProcess中会更新Dialog中的进度条
private void onThreadDownloadApkProcess(Message msg) {
if (null == this.mUpgradeDialog) {
this.mUpgradeDialog = UpgradeDialogFragment.newInstance();
this.mUpgradeDialog.show(getSupportFragmentManager(), "dialog_upgrade"); //Dialog中的view此时还未创建,一直要等到Dialog onStart方法后调用后view才创建完成
} else {
Dialog dialog = (null != this.mUpgradeDialog ? this.mUpgradeDialog.getDialog() : null);
if (null != dialog && dialog.isShowing()) {
Bundle bundle = msg.getData();
int process = bundle.getInt(ServiceAsync.ASYNC_RESULT, 0);
this.mUpgradeDialog.updateProgress(process);
}
}
}