Android dialog usage

Source: Internet
Author: User
Tags case statement

Summary: Create dialog box A dialog box is typically a small window that appears above the current activity. The activity below loses focus, and the dialog accepts all user interaction. Dialog boxes are typically used to cue information and small functions that are directly related to the current application. The Android API supports the following types of ...

Create dialog box
A dialog box is typically a small window that appears on top of the current activity. The activity below loses focus, and the dialog accepts all user interaction. Dialog boxes are typically used to cue information and small functions that are directly related to the current application.
The Android API supports the following types of dialog box objects:
Warning dialog box Alertdialog: A dialog box that can have a list of 0 to 3 buttons, a single box, or a check box. The warning dialog box can be used to create most of the interactive interface, which is the recommended type.
Progress dialog box ProgressDialog: Displays a progress loop or a progress bar. Because it is an extension of alertdialog, it also supports buttons.
Date selection dialog box Datepickerdialog: Let the user select a date.
Time selection dialog box Timepickerdialog: Let the user choose a time.
If you want to customize your dialog box, you can extend the dialog class.
Showing a Dialog Display dialog box
A dialog box is always created and displayed as part of an activity. You should create a dialog box in the activity's oncreatedialog (int). When you use this callback function, the Android system automatically manages the status of each dialog box and connects them to the activity, turning activity into the "owner" of the dialog box. This way, each dialog inherits some properties from the activity. For example, when a dialog box opens, the menu key displays the activity's menus, and the volume key adjusts the volume of the audio stream that the activity is currently using.
Note: If you want to create a dialog box outside of the Oncreatedialog () method, it will not be attached to the activity. You can use Setowneractivity (activity) to attach it to the activity.
When you want to display a dialog box, call ShowDialog (int) and pass the ID of the dialog box to it.
When a dialog box is requested for the first time, Android calls Oncreatedialog (int). Here is where you initialize the dialog box. This callback function passes in the same ID as showdialog (int). After the dialog box is created, the created object is returned.
Android also calls Onpreparedialog (int, Dialog) before the dialog box is displayed. If you want to have dynamically changed content each time the dialog box is displayed, rewrite the function. This function is called every time a dialog box is opened. If you do not define the function, the dialog box is the same every time you open it. The function also passes in the ID of the dialog box and the dialog object you created in Oncreatedialog ().
The best way to define Oncreatedialog (int) and onpreparedialog (int, Dialog) is to use a switch statement to check the incoming ID. Each case creates a corresponding dialog box. For example, a game uses two dialogs: one to indicate the game is paused, and the other to indicate the end of the game. First, define id:static final int dialog_paused_id = 0 for them;
static final int dialog_gameover_id = 1;
Then, add a switch statement in Oncreatedialog (int):
protected Dialog oncreatedialog (int id) {    Dialog Dialog;    Switch (ID) {case dialog_paused_id://Does the work to define the '        pause DIALOG break        ;    Case DIALOG_GAMEOVER_ID://Does the work to        define the game over DIALOG break        ;    Default:        dialog = null;    }    

Note: In this example, the case statement is empty because the program that defines dialog is described later.
In the need to display the dialog box is, call ShowDialog (int), the ID of the incoming dialog box:
ShowDialog (dialog_paused_id);D ismissing A DIALOG dismiss dialog box
When you are ready to close the dialog box, you can use the dismiss () function. You can also call DismissDialog (int) from activity if you want, and the effect is the same.
If you use Oncreatedialog (int) to manage the state of your dialog box, the State of the dialog object will be saved by the activity every time your dialog box is dismissed. If you decide that you no longer need this object or need to clear the State of the dialog box, you should call Removedialog (int). This will remove all internal references to the object, and if the dialog box is displayed, it will be dismissed.
Use dismiss listeners using the dismiss listener
If you want to run some programs when the dialog box is dismissed, you should attach a cancellation listener to the dialog box.
The Dialoginterface.ondismisslistener interface is defined first. This interface has only one method, Ondismiss (Dialoginterface), which is called when the dialog box is dismissed.
Then pass your Ondismisslistener implementation to Setondismisslistener ().
However, note that the dialog box can also be "canceled". This is a special case, which means that the dialog box is explicitly canceled by the user. This occurs when the user presses the "back" key, or when the dialog box explicitly calls Cancel () (pressing the Cancel button of the dialog box). Ondismisslistener will still be notified when a dialog box is canceled, but you should use Setoncancellistener () if you want to be notified when the dialog box is displayed as canceled (instead of normal) Register a Dialoginterface.oncancellistener.
Creating an Alertdialog Create warning dialog box
An alertdialog was an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs this use any of the following features:
A warning dialog box is an extension of the dialog box. It is able to create most dialog box user interfaces and is the recommended dialog box class Nova. You should use it for a dialog box that requires any of the following features:
A title
A text message
1 x-3 buttons
An optional list (radio box or check box)
To create a alertdialog, use the Alertdialog.builder subclass. Use Alertdialog.builder (Context) to get a Builder, and then use the public method of the class to define the properties of the Alertdialog. Once set, use the Create () method to get the Alertdialog object.
The following topics show how to define different properties for Alertdialog, using the Alertdialog.builder class. If you use these sample code, you can return the last dialog object in Oncreatedialog () to get the effect of the dialog box in the picture.
Adding buttons Add button

To create a window, use the set ... Button () Method:

Alertdialog.builder Builder = new Alertdialog.builder (this), Builder.setmessage ("is sure you want to exit?")       . Setcancelable (False)       . Setpositivebutton ("Yes", new Dialoginterface.onclicklistener () {public           void OnClick ( Dialoginterface dialog, int id) {                MyActivity.this.finish ();           }       })       . Setnegativebutton ("No", new Dialoginterface.onclicklistener () {public           void OnClick (dialoginterface dialog, int ID ) {                dialog.cancel ();           }       }). Show (); Alertdialog alert = Builder.create ();
First, use Setmessage (charsequence) to add a message to the dialog box. Then, you start to call the method consecutively, using Setcancelable (Boolean) To set the dialog box to not be canceled (you cannot use the back key to cancel). For each button, use set ... button () method that accepts the button name and a dialoginterface.onclicklistener that defines the action that should be taken when the user selects the button.
Note: For each type of button, you can only create one for Alertdialog. In other words, a alertdialog cannot have more than two "positive" buttons. This makes the number of possible buttons up to three: affirmative, negative, neutral. These names are not associated with actual functions, but will help you remember what they do. Adding a list additions

To create a alertdialog with optional options, use the Setitems () method

Final charsequence[] items = {"Red", "Green", "Blue"}; Alertdialog.builder Builder = new Alertdialog.builder (this), Builder.settitle ("Pick a Color"), Builder.setitems (items, New Dialoginterface.onclicklistener () {public    void OnClick (dialoginterface dialog, int item) {        Toast.maketext (Getapplicationcontext (), Items[item], Toast.length_short). Show ();    }); Alertdialog alert = Builder.create ();
First add a title. Then use Setitems () to add an optional list that accepts a list of option names and a dialoginterface.onclicklistener, which defines the response for the option.
Adding checkboxes and radio buttons add a radio box and check box

To create a dialog box with a multiple-selection list or a single-selection list, use the Setmultichoiceitems () and Setsinglechoiceitems () methods. If you create a selectable list in Oncreatedialog (), Android automatically manages the status of the list. As long as activity remains active, the dialog remembers the option you just selected, but the selection is lost when the user exits the activity.
Note: To save your selections when your acitivity leaves and pauses, you must save and restore the settings correctly in the activity's declaration cycle. In order to persist the selection, you must use one of the data storage technologies.
To create a alertdialog with a single-selection list, simply change the Setitems () in one example to Setsinglechoiceitems ():

Final charsequence[] items = {"Red", "Green", "Blue"}; Alertdialog.builder Builder = new Alertdialog.builder (this); Builder.settitle ("Pick a Color"); Builder.setsinglechoiceitems (items,-1, New Dialoginterface.onclicklistener () {public    void OnClick ( Dialoginterface dialog, int item) {        Toast.maketext (Getapplicationcontext (), Items[item], toast.length_short). Show ();    }}); Alertdialog alert = Builder.create ();
The second parameter is the default selected option location, using "1" to indicate that no option is selected by default.
Creating A ProgressDialog Create progress dialog box

A ProgressDialog (Progress dialog box) is an extension of alertdialog. It can show a progress animation-progress loop or progress bar. This dialog box can also provide buttons, such as canceling a download, and so on.
It is very simple to open a progress dialog box, just call Progressdialog.show (). For example, the dialog box can be displayed directly without Oncreatedialog (int):
ProgressDialog dialog = Progressdialog.show (Myactivity.this, "",
"Loading. Please wait ... ", true);
The first parameter is an application context. The second is the title of the dialog box (empty here), the third is the dialog box content, and the last one is whether the progress is not deterministic (this is only related to the creation of the progress bar, see the next section).
The default style of the progress dialog box is a rotated ring. If you want to show progress values, see the next section.
Showing a progress bar display progress bar
Use an animation progress bar to display progress:
Use the ProgressDialog (Context) constructor to initialize a ProgressDialog object.
Set the progress style to "style_horizontal", using the Setprogressstyle (int) method. and set other properties, such as content.
Call Show () or return the ProgressDialog from the Oncreatedialog (int) callback function when it needs to be displayed.
You can use setprogress (int) or Incrementprogressby (int) To increase the progress of the display.
For example, your settings might look like this: ProgressDialog ProgressDialog;
ProgressDialog = new ProgressDialog (mcontext);
Progressdialog.setprogressstyle (progressdialog.style_horizontal);
Progressdialog.setmessage ("Loading ...");
Progressdialog.setcancelable (FALSE);
Settings are simple. Most of the code required to create a progress dialog box is in the process of updating it. You may need to update it in a new thread and use handler to report progress to the activity. If you are unfamiliar with handler and other threads, consider the following example, which uses a new thread to update the progress.
Example ProgressDialog with a second thread example-using a thread to display a progress dialog box
This example uses a thread to track the progress of a process (in fact, from 1 to 100). Whenever a progress update occurs, the thread sends a message to the main activity through handler. Main activity update Progressdialog.package Com.example.progressdialog;

Import Android.app.activity;import android.app.dialog;import android.app.progressdialog;import android.os.Bundle; Import Android.os.handler;import Android.os.message;import Android.view.view;import    Android.view.view.onclicklistener;import Android.widget.button;public class Notificationtest extends Activity {    static final int progress_dialog = 0;    Button button;    Progressthread Progressthread;    ProgressDialog ProgressDialog; /** called when the activity is first created.        */public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);         Setcontentview (R.layout.main);        Setup the button that starts the progress Dialog button = (button) Findviewbyid (R.id.progressdialog); Button.setonclicklistener (New Onclicklistener () {public void OnClick (View v) {ShowDialog (Progre            Ss_dialog);    }        }); } protected Dialog oncreatedialog (int id) {switch (ID) {Case progress_dIalog:progressdialog = new ProgressDialog (notificationtest.this);            Progressdialog.setprogressstyle (progressdialog.style_horizontal);            Progressdialog.setmessage ("Loading ...");            Progressthread = new Progressthread (handler);            Progressthread.start ();        return progressdialog;        Default:return null;  }}//Define the Handler that receives messages from the thread and update the progress final Handler Handler =            New Handler () {public void Handlemessage (Message msg) {int total = Msg.getdata (). GETINT ("Total");            Progressdialog.setprogress (total);                if (total >=) {dismissdialog (progress_dialog);            Progressthread.setstate (Progressthread.state_done);     }        }    };        /** Nested class that performs progress calculations (counting) */private class Progressthread extends Thread {        Handler Mhandler; Finalstatic int state_done = 0;        Final static int state_running = 1;        int mstate;        int total;        Progressthread (Handler h) {mhandler = h;               public void Run () {mstate = state_running;            Total = 0;                while (mstate = = state_running) {try {thread.sleep (100);                } catch (Interruptedexception e) {log.e ("ERROR", "Thread interrupted");                } Message msg = Mhandler.obtainmessage ();                Bundle B = new bundle ();                B.putint ("Total", total);                Msg.setdata (b);                Mhandler.sendmessage (msg);            total++; }}/* Sets the current state for the thread, * used to stop the thread */public void Setsta        Te (int.) {mstate = state; }    }}

Creating a custom Dialog Create a customization dialog box

If you want to customize a dialog box, you can use layout elements to create the layout of your dialog box. When the layout is defined, pass the root view object or the layout resource ID to Setcontentview (view).
For example, create a dialog box:
Create an XML layout custom_dialog.xml:

Http://schemas.android.com/apk/res/android "              android:id=" @+id/layout_root "              android:orientation=" Horizontal "              android:layout_width=" fill_parent "              android:layout_height=" fill_parent "              android:padding = "10DP"              >                   android:layout_width= "wrap_content"               android:layout_height= "Fill_parent"               Android : layout_marginright= "10DP"               />                  android:layout_width= "wrap_content"              android:layout_height= " Fill_parent "              android:textcolor=" #FFF "              />

The XML defines a imageview and a textview in a linearlayout.
Set the above layout as the content view of the dialog box, and define the contents of ImageView and TextView:

Context Mcontext = Getapplicationcontext ();D ialog Dialog = new Dialog (mcontext); Dialog.setcontentview (R.layout.custom_dialog);d ialog.settitle ("Custom Dialog"); TextView Text = (TextView) Dialog.findviewbyid (R.id.text); Text.settext ("Hello, this is a custom dialog!"); Mageview image = (ImageView) Dialog.findviewbyid (r.id.image); Image.setimageresource (r.drawable.android);

After initializing dialog, use Setcontentview (int) to pass the layout resource ID to it. Now that Dialog has a well-defined layout, you can use Findviewbyid (int) to find the ID of the element and modify its contents.
Use the method described earlier to display the dialog box.
A dialog box created using the dialog class must have a caption. If you do not call Settitle (), the title area is left blank. If you do not want to have a title, then you should use the Alertdialog class to create a custom dialog box. However, because a alertdialog uses the Alertdialog.builder class to build the most convenient, you have no way to use Setcontentview (int), but you can only use Setview (View). This method accepts a view object, so you need to expand your root view from the XML.
To expand an XML layout, use Getlayoutinflater () (or Getsystemservice ()) to get the Layoutinflater, and then call inflate (int, viewgroup), the first parameter is the layout ID, The second parameter is the ID of the root view. You can now use the expanded layout to find the View object and define the contents of the ImageView and TextView elements. Then instantiate the Alertdialog.builder and use Setview (View) to set the expanded layout for the dialog box. For example:

Alertdialog.builder Builder; Alertdialog Alertdialog; Context Mcontext = Getapplicationcontext (); Layoutinflater Inflater = (layoutinflater) mcontext.getsystemservice (Layout_inflater_service); View layout = Inflater.inflate (R.layout.custom_dialog,                               (viewgroup) Findviewbyid (r.id.layout_root)); TextView Text = (TextView) Layout.findviewbyid (R.id.text); Text.settext ("Hello, this is a custom dialog!"); Mageview image = (ImageView) Layout.findviewbyid (r.id.image); Image.setimageresource (r.drawable.android); builder = New Alertdialog.builder (Mcontext); Builder.setview (layout); Alertdialog = Builder.create ();

Use the Alertdialog Customize dialog box to take advantage of its built-in features such as buttons, select lists, headings, icons, and more.

Android dialog usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.