我想在屏幕上使用进度条而不是进度对话框。
我已经在XML视图文件中插入了一个进度条,我希望在加载时显示它,并在不加载时禁用它。
因此,我使用了“visible”,但它会占用空间,导致其他数据下移。
我应该如何在AsyncTask中使用进度条?如何显示和隐藏它?
我想在屏幕上使用进度条而不是进度对话框。
我已经在XML视图文件中插入了一个进度条,我希望在加载时显示它,并在不加载时禁用它。
因此,我使用了“visible”,但它会占用空间,导致其他数据下移。
我应该如何在AsyncTask中使用进度条?如何显示和隐藏它?
以下是一个最详尽的示例:
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
的区别在于进度条不会被绘制,但仍占据其空间(对于某些布局很有用)。
当使用异步任务中的进度条时,您可以使用doInBackground(int Progress)
中的PostPrgressUpdate()
方法,并在OnProgressUpdate()
方法中相应地更新进度条。至于进度条的显示和隐藏,我无法理解您的问题(或问题,请修正)。
在 XML 中使用
<ProgressBar
android:id="@+id/progress_bar"
style="@android:style/Widget.ProgressBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
然后在Asyntask中
ProgressBar mProgress=(ProgressBar) findViewById(R.id.progress_bar);
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mProgress.setVisibility(View.GONE);
}