AlertDialog.Builder

怎样用AlertDialog.Builder显示进度条

小樊
81
2024-10-12 21:11:22
栏目: 编程语言

要使用AlertDialog.Builder显示进度条,请按照以下步骤操作:

  1. 首先确保您的项目中已经导入了androidx.appcompat:appcompatandroidx.core:core库。如果没有,请在build.gradle文件中添加依赖项:
dependencies {
    implementation 'androidx.appcompat:appcompat:版本号'
    implementation 'androidx.core:core:版本号'
}
  1. 在您的Activity或Fragment中创建一个方法,例如showProgressDialog(),并在其中设置AlertDialog和进度条:
private void showProgressDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    ProgressBar progressBar = new ProgressBar(this);
    builder.setView(progressBar);
    builder.setCancelable(false); // 设置为false,使对话框无法被取消
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}
  1. 在需要显示进度条的地方调用showProgressDialog()方法。例如,当您开始一个耗时操作时:
new Thread(new Runnable() {
    @Override
    public void run() {
        // 执行耗时操作
        try {
            Thread.sleep(3000); // 假设操作需要3秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 操作完成后,回到主线程更新UI
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 关闭进度条对话框
                AlertDialog alertDialog = getAlertDialog();
                if (alertDialog != null && alertDialog.isShowing()) {
                    alertDialog.dismiss();
                }
            }
        });
    }
}).start();

// 显示进度条对话框
showProgressDialog();

这样,当耗时操作开始时,会显示一个包含进度条的AlertDialog。操作完成后,进度条将自动消失。

0
看了该问题的人还看了