When you want to perform time-consuming operations, you will often see the "Please wait" dialog box. For example, if a user is logging on to the server and does not allow the user to use the software, or the application needs to perform some time-consuming calculations before returning the results to the user. In these cases, a "progress bar" dialog box is displayed to allow users to wait and prevent users from performing unnecessary operations.
1. Create a project: Dialog.
2. Code in main. xml.
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: orientation = "vertical">
<Button
Android: id = "@ + id/btn_dialog2"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: onClick = "onClick2"
Android: text = "Click to display a progress dialog"/>
</LinearLayout>
3. Code in DialogActivity. java. Package net. horsttnann. Dialog;
Import net. horsttnann. Dialog. R;
Import android. app. Activity;
Import android. app. ProgressDialog;
Import android. OS. Bundle;
Import android. view. View;
Public class DialogActivity extends Activity {
ProgressDialog progressDialog;
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
}
Public void onClick2 (View v ){
// --- Show the dialog ---
Final ProgressDialog dialog = ProgressDialog. show (this,
"Doing something", "Please wait...", true );
New Thread (new Runnable (){
Public void run (){
Try {
// --- Simulate doing something lengthy ---
Thread. sleep (5000 );
// --- Dismiss the dialog ---
Dialog. dismiss ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}). Start ();
}
} Www.2cto.com
4. Press F11 for debugging and click the button to bring up the "progress bar" dialog box.
Basically, to create a "progress bar" dialog box, you only need to create an instance of the ProgressDialog class and then call the show () method:
// --- Show the dialog ---
Final ProgressDialog dialog = ProgressDialog. show (this,
"Doing something", "Please wait...", true );
Because it is a "Modal" dialog box, it will cover other UI components until they are removed. If you want to execute a "long-term running" task in the background, you can create a thread. The code in the run () method will be executed in an independent thread. The following code uses the sleep () method to simulate a background task that takes 5 seconds to execute: new Thread (new Runnable (){
Public void run (){
Try {
// --- Simulate doing something lengthy ---
Thread. sleep (5000 );
// --- Dismiss the dialog ---
Dialog. dismiss ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}). Start ();
Five seconds later, execute the dismiss () method, and the dialog box is removed.
From manoel's column