android - 进度对话框显示太晚

标签 android android-asynctask progressdialog

我有一个应用程序,我想执行以下操作:

  1. 显示带有按钮和 TextView 的 Activity 。
  2. 用户点击按钮,应用会显示一个进度对话框。
  3. 应用调用网络服务来获取列表。
  4. 隐藏进度对话框,出现列表选择对话框以显示检索到的列表。
  5. 用户选择列表中的一项。
  6. 项目显示在 TextView 中。

问题是发生了这种情况:

  1. 显示带有按钮和 TextView 的 Activity 。
  2. 用户点击按钮,按钮状态变为选中状态。
  3. 几秒钟后,列表选择对话框出现,显示检索到的列表。
  4. 用户选择列表中的一项。
  5. 进度对话框显示几秒钟,然后隐藏。
  6. 项目显示在 TextView 中。

Web 服务在 AsyncTask 中执行,进度对话框显示在 onPreExecute() 方法中,并在 onPostExecute() 方法中关闭:

public class WebService extends AsyncTask<Void, Void, Boolean> {

  public void onPreExecute() {
    _progressDialog = ProgressDialog.show(_context, "", message);
  }

  protected Boolean doInBackground(Void... params) {
    try {
      // Execute web service
    }
    catch (Exception e) {
      e.printStackTrace();
    }

    return true;
  }

  protected void onPostExecute(Boolean result) {
    _progressDialog.hide();
  }
}

执行网络服务和显示对话框的代码:

WebService ws= new WebService();
ws.execute();

// Web service saves retrieved list in local db

// Retrieve list from local db

AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setTitle("Select an Item");
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(context,
        android.R.layout.simple_selectable_list_item, list);
db.setAdapter(listAdapter, null);
db.show();

我是否需要在代码中添加一些内容以确保进度对话框显示在“列表选择”对话框之前?

提前谢谢你。

最佳答案

这是我的做法:

public OnClickListener loginListener = new OnClickListener() {
    public void onClick(View v) {
        ProgressDialog progressDialog = new ProgressDialog(activity);
        progressDialog.setMessage("Logging in...");
        LoginTask loginTask = new LoginTask(activity, progressDialog, loginLayout, loggedInLayout);
        loginTask.execute();
    }
};

异步任务:

protected void onPreExecute() {
    progressDialog.show();
}

protected void onPostExecute(Integer responseCode) {
if (responseCode == 1) {
        progressDialog.dismiss();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(activity.getApplicationContext(), "Logged in.", duration);
        toast.show();
        activity.bar.getTabAt(0).setText(dbHandler.getUserDetails().get("email"));

因此,我实际上在主 Activity 中创建了 ProgressDialog 并在声明/执行任务之前设置了它的消息。然后,任务显示并关闭(而不是隐藏)对话框。

让我知道这是否可行!

关于android - 进度对话框显示太晚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900588/

相关文章:

android - 根据 TextView 内的文本更改 TextView 的颜色

java - 由于整数赋值导致的 Android 迭代错误

android - 使用 tcp 套接字连接 android 模拟器

java - AsycTask 不执行

未调用 PreExecute 方法上的 Android Asynctask

android - 获取位置 android Kotlin

java - Android AsyncTask onPostExecute 访问 GUI 元素给出空指针

java - Android ProgressDialog 位于另一个对话框中

android - 如何在没有消息的情况下显示进度对话框(我只需要不确定的圆圈)?

java - 处理 Firebase 身份验证和数据库实时事务之间的最佳方式