微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – Progressbar与asyncTask共享

我想在屏幕上使用进度条而不是progressDialog.

我在我的XML视图文件中插入了一个progressBar,我希望它在加载时显示,并在加载时禁用它.

所以我使用可见,但它发生了,所以其余的数据下降.

我应该如何在asynctask中使用progressbar?我该如何显示和隐藏它?

解决方法:

这是一个最详尽的例子:

public class ScreenSplash extends Activity {

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_splash);

        final ProgressBar progress = (ProgressBar)findViewById(R.id.progress);
        final TextView    textview = (TextView)findViewById(R.id.text);

        new MyWorker(this, progress, textview).execute();
    }
}


final class MyWorker extends AsyncTask<Void, Integer, Void> {
    private static final int titles[] = {R.string.splash_load_timezone,
                                         R.string.splash_load_memory,
                                         R.string.splash_load_genres,
                                         R.string.splash_load_channels,
                                         R.string.splash_load_content};
    private static final int progr[]  = {30, 15, 20, 25, 20};

    private int index;

    private final Activity parent;
    private final ProgressBar progress;
    private final TextView textview;

    public MyWorker(final Activity parent, final ProgressBar progress, final TextView textview) {
        this.parent = parent;
        this.progress = progress;
        this.textview = textview;
    }

    @Override
    protected void onPreExecute() {
        int max = 0;
        for (final int p : progr) {
            max += p;
        }
        progress.setMax(max);
        index = 0;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected Void doInBackground(final Void... params) {
        /* Load timezone. this is very slow - may take up to 3 seconds. */
          ...
        publishProgress();

        /* Get more free memory. */
          ...
        publishProgress();

        /* Load channels map. */
          ...
        publishProgress();

        /* Load genre names. */
          ...
        publishProgress();


        /* Preload the 1st screen's content. */
          ...
        publishProgress();

        return null;
    }

    @Override
    protected void onProgressUpdate(final Integer... values) {
        textview.setText(titles[index]);
        progress.incrementProgressBy(progr[index]);
        ++index;
    }

    @Override
    protected void onPostExecute(final Void result) {
        parent.finish();
    }
}

显示/隐藏进度条,请使用progress.setVisibility(View.VISIBLE)和progress.setVisibility(View.GONE).还有View.INVISIBLE常量;它与GONE的区别在于您的进度条未绘制但仍占用其空间(对于某些布局很有用).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐