Progressbar与asyncTask结合使用

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

我已经在我的XML-view文件中插入了一个progressBar,我想在加载时显示它,并在不加载时将其禁用。

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

我应该如何使用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(); } } 

对于shownig /隐藏你的进度条,使用progress.setVisibility(View.VISIBLE)progress.setVisibility(View.GONE) 。 还有View.INVISIBLE常量; 它与GONE区别在于你的进度条没有被绘制,但仍然占据着它的空间(对某些布局有用)。

至于从asynchronous任务使用进度栏,您可以使用doInBackground(int Progress)OnProgressUpdate()方法中的OnProgressUpdate()更新ProgressBar。 至于显示和隐藏的酒吧,我无法理解你的问题(或问题请修改)

在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); }