Dialog Use of Android UI

Source: Internet
Author: User
Tags throw exception

Dialog Use of Android UIIntroduction

In today's applications, Dialog is widely used. Often used to prompt the user for some information.

Using Dialog in your application

There are a variety of Dialog available in the Android system for our use, and we don't need to do it ourselves.

    • Alertdialog is a multi-function Dialog that can display a title, content, up to three buttons, or a normal list, a radio list, a multi-select list, or a custom space.
    • Datepickerdialog and Timepickerdialog are used for display.

The Android system has defined these Dialog styles and structures for us, and we just need to invoke the appropriate method.

Dialog is the base class for all dialogs, and we can create dialogs directly using Dialog. However, Android officially recommends that we use the Dialogfragment class instead of using Dialog directly to create dialogs, and the Dialogfragment class provides all the ways you can create Dialog and control its appearance. and using dialogfragment to manage Dialog can ensure that Dialog correctly handles the event of its life-recycling.

The following shows how to create a Dialog with title, content, and two buttons. First, inherit dialogfragment and rewrite its Oncreatedialog () method:

public class Traditionaldialogfragment extends Dialogfragment {    @Override public    Dialog Oncreatedialog (Bundle Savedinstancestate) {        //Create Alertdialog object        alertdialog.builder Builder = new Alertdialog.builder (getactivity () );        Set the title, content, and button for the Dialog object.        Builder.settitle ("title")            . Setmessage ("This is message!")            . Setpositivebutton ("Positive", new Dialoginterface.onclicklistener () {public                void OnClick (Dialoginterface dialog , int id) {                    //do Something                }            })            . Setnegativebutton ("negative", new Dialoginterface.onclicklistener () {public                void OnClick (Dialoginterface dialog, int. ID) {                    //do something                }            });        Creates a new Dialog and returns to the caller return        builder.create ();}    }

Then, in Activity, we create a dialogfragment and call the show () method in it to display the Dialog:

Dialogfragment newfragment = new Traditionaldialogfragment () Newfragment.show (Getfragmentmanager (), "DialogTest");

The show () method works by displaying a Dialog and handing Fragment to the Fragmentmanager we provide (obtained through the Getfragmentmanager () method).
where "Dialogtest" is a unique token that the system uses to save and restore the Fragment state when necessary.

Several types of Alertdialog

As mentioned earlier, there are several types of alertdialog, which are described here:

Normal type

Set the caption for Dialog by calling the Settitle () method:

Builder.settitle ("title");

Of course, you can also load the title from the resource file. Suppose a string resource named Dialog_title already exists:

Builder.settitle (R.string.dialog_title);

Below, set the body of the display for Dialog:

Builder.setmessage ("This is message!");

Because the return type is Builder, you can also use it directly:

Builder.settitle ("title")    . Setmessage ("This is message!");

Of course, you can also use resources. Dialog has a maximum of three buttons:

    • Positive This is our common "OK, continue" button.
    • Negative is mainly the "Cancel" we usually use.
    • Neutral This button in the middle of Positive and negative, often used to "remind later"

We can add buttons and handle the corresponding events in the following way:

Builder.setnegativebutton (Android. R.string.cancel, New Dialoginterface.onclicklistener () {    @Override public    void OnClick (dialoginterface dialog, int id) {    }});

The first parameter is used to set the text that appears on the button, where I use the cancel that comes with Android itself. The latter parameter identifies the corresponding Click event code for the button setting. If you want to use the other two kinds of buttons, directly change the negative into other.

Normal List

When we need to make the pop-up menu Class A listdialog, we can also use the List provided by Alertdialog directly.

We can add the list Item to Dialog in the following ways:

Builder.setitems (Android. R.array.emailaddresstypes, New Dialoginterface.onclicklistener () {    @Override public    void OnClick ( Dialoginterface dialog, int which) {    }});

Setitems adds a series of data to the Dialog for the List. The first parameter is the corresponding data, and here I use an array of Android's own data, which can be defined by itself. Second parameter This is the code for the List corresponding user action, which represents the index of the item selected by the user. Of course, you can also use the Setadapter () method to pass in a listadapter to dynamically add data to the List.

Note that the list is full of the Dialog content section, so you cannot display both the Message and the list. Also, once a user clicks on an Item in the list, it triggers the destruction of the Dialog event, so there's no need to add a Button to it (if you want to).

Radio List

The radio list displays a radio button (radio buttons) after the Item:

This is basically the same as the normal list, but it does not trigger the Destroy event after clicking on the item like the normal list, so we still need to provide a button to destroy the Dialog. Adding data is similar to the normal List, just change the setitems to Setsinglechoiceitems ().

Multi-Select List

Sometimes you need to select multiple data at the same time, you can use Multiplelist:

Using Multipledialog only needs to replace Setsinglechoiceitem in singlelist with the following code:

Builder.setmultichoiceitems (Android. R.array.emailaddresstypes, NULL,        new Dialoginterface.onmultichoiceclicklistener () {    @Override    public void OnClick (Dialoginterface dialog, int which,                        boolean isChecked) {        //do Something    }})

It is a good way to say whether isChecked is chosen because we may need to record the user's choice. We can use a ArrayList to store user-selected items:

ArrayList mselecteditems = new ArrayList ();

and add the following code to the OnClick to record the data:

if (isChecked) {   //If the user checked the item, add it to the selected items   mselecteditems.add (which);} else if (Mselecteditems.contains (which)) {   //Else, if the item is already in the array, remove it   mselecteditems.remove (integer.valueof (which));}

Tip: For this kind of control (mulitiple, single) that can feed back the user's choice of information, sometimes it may be necessary to select some of the user's original data at initialization time.

Self-defined Dialog

Sometimes it is necessary to implement a login interface in Dialog, but there is no ready-made Dialog for us to use in Android, and Customdialog comes in handy. The content section in the middle of the alertdialog allows the user to define the Layout themselves and add them to the Alertdialog by Setview ():

By default, the layout of the settings is filled with the entire Dialog, but we can still add Title and Button to it. Take a login interface as an example to demonstrate how to use Customdialog.

First, you have to add layout file layouts:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "vertical" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" > <imageview android:src= "@draw Able/head_logo "android:layout_width=" match_parent "android:layout_height=" 64DP "android:scaletype=" C        Enter "android:background=" #FFFFBB33 "android:contentdescription=" @string/app_name "/> <edittext Android:id= "@+id/dialog_username" android:inputtype= "textemailaddress" android:layout_width= "Match_pare NT "android:layout_height=" Wrap_content "android:layout_margintop=" 16DP "android:layout_marginleft=" 4 DP "android:layout_marginright=" 4DP "android:layout_marginbottom=" 4DP "android:hint=" @string/username "/> <edittext android:id=" @+id/dialog_password "android:layout_width=" Match_parent "Android    : layout_height= "Wrap_content"    android:layout_margintop= "4DP" android:layout_marginleft= "4DP" android:layout_marginright= "4DP" a Ndroid:layout_marginbottom= "16DP" android:hint= "@string/password" android:inputtype= "Textpassword"/>< /linearlayout>

Create a View in Fragment with Inflater:

Layoutinflater inflater = getactivity (). Getlayoutinflater ();//Because it is in Dialog, the parent view fills null. View view =  inflater.inflate (r.layout.dialog_signin, null); Builder.setview (view);

Then in the Add button:

Builder.setpositivebutton ("Signin", new Dialoginterface.onclicklistener () {    @Override public    void OnClick ( Dialoginterface dialog, int id) {        //sign in the user ...    }}); Builder.setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {public    void OnClick (dialoginterface dialog, int id) {        //Cancel ...    }});

This will enable the login box.

Return the data to the holder of the Dialog

When the user changes the data and clicks on the confirmation, it needs to return the data to the current Dialog holder. To accomplish this, you first need to define an interface that contains the various types of click events.

Public interface Noticedialoglistener {public    void Ondialogpositiveclick (Object object);    public void Ondialognegativeclick (Object object);    // ...}

Then, let the Activity inherit and implement the appropriate method:

public class Mainactivity extends Activity implements Noticedialoglistener {    //...    .. @Override public    void Ondialogpositiveclick (Object o) {        //does something    }    @Override public    Void Ondialognegativeclick (Object o) {        //do something    }    //...}

Declare a Noticedialoglistener variable in our dialogfragment.

Noticedialoglistener Mlistener;

Now rewrite the Onattach () method in Dialogfragment:

@Overridepublic void Onattach (activity activity) {    Super.onattach (activity);    Verify that the host activity implements the callback interface    try {        //instantiate the Noticedialoglistener s o We can send events to the host        Mlistener = (noticedialoglistener) activity;    } catch (ClassCastException e) {
   
    //the activity doesn ' t implement the interface, throw exception        throw new ClassCastException (Activity.tostring () c8/>+ "must implement Noticedialoglistener");}    }
   

Onattach () Saves the noticedialoglistener part of the Activity object that we passed to Dialogfragment, which is called when we return the data later. Now add the appropriate code to the appropriate event:

Builder.settitle ("title")    . Setmessage ("This is message!")    . Setpositivebutton ("Positive", new Dialoginterface.onclicklistener () {public        void OnClick (Dialoginterface dialog , int id) {            mlistener.ondialogpositiveclick (/* Joins the data to be returned */);        }    })    . Setnegativebutton ("negative", new Dialoginterface.onclicklistener () {public        void OnClick (Dialoginterface dialog , int id) {            mlistener.ondialognegativeclick (/* Joins the data to be returned */);        }    });

This enables the return of the data to the holder of the Dialog. Of course, if a program uses a variety of Dialog, all need to return data, then in our implementation of the Ondialogpositiveclick method, how to determine the data source? There are many ways to write a method for each Dialog, so that it is not only repetitive and inefficient. or rewrite Noticedialoglistener:

Public interface Noticedialoglistener {public    void Ondialogpositiveclick (int type, object object);    public void Ondialognegativeclick (int type, object object);    // ...}

and use switch to match the information where the method is implemented:

public void Ondialogpositiveclick (int type, Object o) {    switch (type) {case        1:    //Traditional            Break;
   case 2:    //List break            ;        // ...        Default: Break            ;    }}

This enables the bearer to pass data back to Dialog.

Destruction of Dialog

If the custom Dialog is not added to the system's own button, we need to implement Dialog's own destruction. The Andorid system allows us to destroy the current Dialog using the dismiss () method in Dialogfragment. There are also ways to perform destruction, such as when the user taps the back button while Dialog is working, or calls the OnCancel () method directly in the code, just like clicking the Cancel button in Dialog.

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.