How:利用ProgressAialog创建进度条

来源:互联网 发布:outlook是什么软件 编辑:程序博客网 时间:2024/06/11 18:46

Creating a ProgressDialog

A ProgressDialog is an extension of theAlertDialogclass that can display a progress animation in the form of a spinning wheel, for a task withprogress that's undefined, or a progress bar, for a task that has a defined progression.The dialog can also provide buttons, such as one to cancel a download.

Opening a progress dialog can be as simple as calling ProgressDialog.show(). For example, the progress dialog shown to the right can be easily achieved without managing the dialog through theonCreateDialog(int) callback,as shown here:

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",                         "Loading. Please wait...", true);

The first parameter is the application Context, the second is a title for the dialog (left empty), the third is the message, and the last parameter is whether the progressis indeterminate (this is only relevant when creating a progress bar, which isdiscussed in the next section).

The default style of a progress dialog is the spinning wheel.If you want to create a progress bar that shows the loading progress with granularity,some more code is required, as discussed in the next section.

Showing a progress bar

To show the progression with an animated progress bar:

  1. Initialize the ProgressDialog with the class constructor, ProgressDialog(Context).
  2. Set the progress style to "STYLE_HORIZONTAL" with setProgressStyle(int) and set any other properties, such as the message.
  3. When you're ready to show the dialog, call show() or return the ProgressDialog from theonCreateDialog(int) callback.
  4. You can increment the amount of progress displayed in the bar by calling eithersetProgress(int) with a value for the total percentage completed so far orincrementProgressBy(int) with an incremental value to add to the total percentage completed so far.
  5. dismiss().

For example, your setup might look like this:

ProgressDialog progressDialog;progressDialog = new ProgressDialog(mContext);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMessage("Loading...");progressDialog.setCancelable(false);

The setup is simple. Most of the code needed to create a progress dialog is actually involved in the process that updates it. You might find that it'snecessary to create a second thread in your application for this work and then report the progressback to the Activity's UI thread with a Handler object. If you're not familiar with using additional threads with a Handler, see the example Activity below that uses a second thread toincrement a progress dialog managed by the Activity.