为什么 setVisibility 在 Android ProgressBar 上不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3659940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:13:02  来源:igfitidea点击:

Why isn't setVisibility working on Android ProgressBar?

androidprogress-bar

提问by Hymannad

It would be nice if the ProgressBar could be made to go away until it is needed. Is there a problem using setVisibility.progressBar in applyMenuChoice? The problem with using setVisibility.progressBar in PrintStatusTask().execute() is that it crashes the app during runtime.

如果 ProgressBar 可以在需要之前消失,那就太好了。在 applyMenuChoice 中使用 setVisibility.progressBar 有问题吗?在 PrintStatusTask().execute() 中使用 setVisibility.progressBar 的问题是它在运行时使应用程序崩溃。

public class Controller extends Activity {
    private ProgressBar progressBar;
    ...

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.controller);
        progressBar = (ProgressBar)findViewById(R.id.progressBar);
        ...

    private boolean applyMenuChoice(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menuStatus:
            progressBar.setVisibility(View.VISIBLE);
            new PrintStatusTask().execute();
            progressBar.setVisibility(View.GONE);
            ...

回答by Mark B

progressBar.setVisibility(View.VISIBLE);
new PrintStatusTask().execute();
progressBar.setVisibility(View.GONE);

This is what you are doing: 1. Show the progressBar 2. Spawn a task on a separate thread 3. Hide the progressBar

这就是你在做什么: 1. 显示进度条 2. 在单独的线程上生成一个任务 3. 隐藏进度条

This entire process is going to take no more than a couple milliseconds to execute. You need to hide the progress bar in the onPostExecute()method of the PrintStatusTask class.

整个过程的执行时间不会超过几毫秒。您需要onPostExecute()在 PrintStatusTask 类的方法中隐藏进度条。

You need to understand that the execute()method of AsyncTaskis a call that executes another thread and doesn't wait for it to finish. That's kind of the whole point of AsyncTask.

你需要明白AsyncTaskexecute()方法是执行另一个线程的调用,而不是等待它完成。这就是 AsyncTask 的全部意义所在。

回答by Paul Burke

Are you trying to hide the ProgressBarin the AsyncTask? If so, it must be done in onPreExecuteor onPostExecute(like all UI commands).

你想把 隐藏在ProgressBarAsyncTask吗?如果是这样,则必须在onPreExecuteor 中完成onPostExecute(就像所有 UI 命令一样)。

Also, use something like this:

另外,使用这样的东西:

private void toggleProgressBar() {
    switch (progressBar.getVisibility()) {
    case View.GONE:
        progressBar.setVisibility(View.VISIBLE);
        break;
    default:
        progressBar.setVisibility(View.GONE);
        break;
    }
}