When you want to do time-consuming operations, you will often see a dialog box with the words "Please wait". For example, users are logging on to a server that does not allow users to use the software at this time, or when the application returns the results to the user, for some time-consuming calculations. In these cases, a "Progress bar" dialog box is displayed, which allows the user to wait in a friendly way, while also preventing users from doing some unnecessary actions.
1. Create a project: Dialog.
2. Code in the 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:o" rientation= "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 the Dialogactivity.java.
public class Dialogactivity extends activity {ProgressDialog progressdialog; /** called the activity is a.
* * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main); public void OnClick2 (View v) {//---Show the dialog---final progressdialo
G 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 (); }
}
4. Press F11 to debug, click on the button, pop-up "Progress bar" dialog box.
Basically, to create a progress bar dialog box, just create an instance of the ProgressDialog class, and then call the show () method:
---Show the dialog---
final progressdialog dialog = Progressdialog.show (this,
doing something, " ... ", true);
Because it's a "modal" dialog, it hides other UI components until it is released. If you want to perform a "long-running" task in the background, you can create a thread. The code inside the Run () method will be executed in a separate thread. The following code uses the Sleep () method to simulate a background task that takes 5 seconds to perform:
New Thread (New Runnable () {public
void run () {
try {
//---simulate doing something lengthy---
thread.sl EEP (5000);
---Dismiss the dialog---
dialog.dismiss ();)
catch (Interruptedexception e) {
e.printstacktrace ();
}
}
). Start ();
After 5 seconds, the dismiss () method is executed, and the dialog box is removed.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/