如何在 Android 中启动活动之前显示进度对话框?

发布于 2024-10-20 13:36:14 字数 66 浏览 1 评论 0原文

在 Android 中,如何在启动 Activity 之前(即 Activity 正在加载一些数据时)显示进度对话框?

How do you display a progress dialog before starting an activity (i.e., while the activity is loading some data) in Android?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

维持三分热 2024-10-27 13:36:14

您应该在 AsyncTask 中加载数据,并在数据加载完成时更新您的界面。

您甚至可以在 AsyncTask 的 onPostExecute() 方法中启动一个新活动。

更具体地说,您将需要一个扩展 AsyncTask 的新类:

public class MyTask extends AsyncTask<Void, Void, Void> {
  public MyTask(ProgressDialog progress) {
    this.progress = progress;
  }

  public void onPreExecute() {
    progress.show();
  }

  public void doInBackground(Void... unused) {
    ... do your loading here ...
  }

  public void onPostExecute(Void unused) {
    progress.dismiss();
  }
}

然后在您的活动中您将执行以下操作:

ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Loading...");
new MyTask(progress).execute();

You should load data in an AsyncTask and update your interface when the data finishes loading.

You could even start a new activity in your AsyncTask's onPostExecute() method.

More specifically, you will need a new class that extends AsyncTask:

public class MyTask extends AsyncTask<Void, Void, Void> {
  public MyTask(ProgressDialog progress) {
    this.progress = progress;
  }

  public void onPreExecute() {
    progress.show();
  }

  public void doInBackground(Void... unused) {
    ... do your loading here ...
  }

  public void onPostExecute(Void unused) {
    progress.dismiss();
  }
}

Then in your activity you would do:

ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Loading...");
new MyTask(progress).execute();
往事随风而去 2024-10-27 13:36:14

当您在 Android 上启动一个长时间运行的进程时,始终建议在另一个线程上执行它。然后,您可以使用 UI 线程显示进度对话框。您无法在进程运行的同一 (UI) 线程中显示进度对话框。

执行以下操作来启动您的流程

pd = ProgressDialog.show(this, "Synchronizing data", "Please wait...");
Thread t = new Thread(this);
t.start();

为此,您的活动应该实现 Runnable

public class SyncDataActivity extends Activity implements Runnable

,如下所示 最后是执行长时间运行的流程的方法

@Override
public void run() {
      //your code here
}

When you start a long-running process on Android, its always advisable to do it on another thread. You can then use the UI thread to display a progress dialog. You cannot display a progress dialog in the same (UI) thread in which the process is running.

Do the following to start your process

pd = ProgressDialog.show(this, "Synchronizing data", "Please wait...");
Thread t = new Thread(this);
t.start();

For this your activity should implement Runnable as follows

public class SyncDataActivity extends Activity implements Runnable

And finally a method to perform the long-running process

@Override
public void run() {
      //your code here
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文