android Dialog使用要点

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);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kmblack1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值