【问题标题】:ProgressBar doesn't show, when using another thread使用另一个线程时,ProgressBar 不显示
【发布时间】:2020-07-14 18:32:05
【问题描述】:

我将循环不确定progressBar 变为可见,然后运行Thread,这可能需要几秒钟(我尝试了AsyncTask,但它不起作用,可能是因为在该方法中运行了另一个AsyncTask)。但是,progressBar 仅在线程完成后才可见。如何在运行线程之前使其可见,以便用户可以看到正在发生的事情?

编辑:代码比较复杂,不长描述就不能全部附上,不过我会尽量附上代码的重要部分

  //this is the Thread class
  private static final class LoadingMolecules extends Thread{
        private Intent intent;
        private ArrayList<Integer> groups;
        Context context;
        QuizProvider quizProvider;

    public LoadingMolecules (Intent intent,ArrayList<Integer> groups, Context context ){
        this.intent = intent;
        this.groups = groups;
        this.context = context;
    }

    @Override
    public void run() {
        quizProvider = new QuizProvider(groups, context);
        //inside next method is the asyncTask
        quizProvider.loadAllCompounds();
    }


}


//there is the code running
progressBar.setVisibility(View.VISIBLE);
        LoadingMolecules lm = new LoadingMolecules(intent, groups, this);
        lm.start();
        try {
            lm.join();
        }catch (InterruptedException ignore){

        }
        intent.putExtra("quizProvider", lm.quizProvider);
        startActivity(intent);
        finish();

【问题讨论】:

  • 可以分享代码吗?
  • @coroutineDispatcher 我尝试添加代码的重要部分。

标签: android android-threading


【解决方案1】:

你应该:

  1. 可见进度。
  2. 启动后台线程。
  3. 在 ui 线程中隐藏进度。

这样:

progress.visibility = View.VISIBLE
AppController.getInstance().getAppExecutors().diskIO().execute(() -> {
   //do stuff
    runOnUiThread(() -> {
         //do stuff
         progress.visibility = View.GONE
    });

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 2012-07-27
    • 2014-07-22
    相关资源
    最近更新 更多