gpt4 book ai didi

android - Progressbar 与 asyncTask 一起

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:54:18 27 4
gpt4 key购买 nike

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

我在我的 XML View 文件中插入了一个进度条,我想让它在加载时显示并在不加载时禁用它。

所以我使用的是可见的,但它发生了,所以其余的数据都下来了。

我应该如何在异步任务中使用进度条?如何显示和隐藏它?

最佳答案

这是一个最详尽的例子:

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 的不同之处在于,您的进度条未绘制但仍占据其空间(对某些布局很有用)。

关于android - Progressbar 与 asyncTask 一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4119009/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com