简体   繁体   English

为什么setVisibility不适用于Android ProgressBar?

[英]Why isn't setVisibility working on Android ProgressBar?

It would be nice if the ProgressBar could be made to go away until it is needed. 如果ProgressBar可以在需要之前消失,那将是很好的。 Is there a problem using setVisibility.progressBar in applyMenuChoice? 在applyMenuChoice中使用setVisibility.progressBar有问题吗? The problem with using setVisibility.progressBar in PrintStatusTask().execute() is that it crashes the app during runtime. 在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);
            ...
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。显示progressBar 2.在单独的线程上生成任务3.隐藏progressBar

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. 您需要在PrintStatusTask类的onPostExecute()方法中隐藏进度条。

You need to understand that the execute() method of AsyncTask is a call that executes another thread and doesn't wait for it to finish. 您需要了解AsyncTaskexecute()方法是一个执行另一个线程并且不等待它完成的调用。 That's kind of the whole point of AsyncTask. 这就是AsyncTask的重点。

Are you trying to hide the ProgressBar in the AsyncTask ? 您是否试图在AsyncTask隐藏ProgressBar If so, it must be done in onPreExecute or onPostExecute (like all UI commands). 如果是这样,它必须在onPreExecuteonPostExecute (与所有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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM