Android Application Development: Dialog uses 123 and androiddialog

Source: Internet
Author: User

Android Application Development: Dialog uses 123 and androiddialog
Introduction


In Android development, we usually use Dialog in many cases, that is, the pop-up box. If a logon dialog box is displayed, you need to confirm the operation again. This article describes how to correctly use the Dialog during Android development.


Design Philosophy of Dialog


Dialog is a Dialog box that prompts you to confirm the next operation (this operation is not executed before confirmation) or display additional information (for example, the user must know the information in the Next Step ). Since it is a pop-up box, it should not be full of full screen (usually), and it should be as short and concise as possible to express what you want to display to the user, removing all redundant information. A standard Dialog is displayed:


1. Title Bar.

It is used to introduce what the Dialog is used for, for example, to describe what the user is requesting or what the application is requesting. The title can be displayed in either a single text or an icon or text.


The official suggestion is that if Dialog is used to warn users, they can directly display the content to tell users that an important event is about to happen without a title. Some important items for users, such as data loss, carrier traffic generation, and consumption actions, are better to use the most direct words as the title and then make a clear description in the content. For example, if a consumption action is generated, the title can be "Checked Out". The content is used to indicate in detail what the account is closed and what the details are. It is best not to start a title like "warning", because it can be expressed by an icon representing the warning.


2. content.

Dialog is mainly used to display content. It can display multiple types of content, such as an important descriptive discourse. It can also be a single choice or a multi-choice list, it can even be any view customized by the developer. The most important thing to note is to control the details or simplicity of the content. if the content is too small, you can consider using Toast for display through interactive modification, after all, the Dialog interface will block user operations. A Dialog with a small amount of content may make the user feel harmless and even think that this prompt is not important, thus reducing the user experience of the application or misoperation.

By the way, the most terrible Android virus (automatically sending text messages and spreading itself) that came out on the Internet a while ago is actually the result of abuse of Android permissions. It can be seen that if you do not provide necessary reminders or prompts for some important actions, this application is similar to "virus" in some ways.


3. Action Buttons


A maximum of two buttons, one for confirmation and one for cancellation. For example, if the content is a single-choice list, you can understand that the clicked content is "OK", so the "cancel" button is not required, the "cancel" button is not required even when the Dialog button is allowed to be canceled by pressing the return button or clicking an area outside the Dialog button. That is to say, the action button can be 2, 1, or none. The specific design logic is determined based on the specific role of Dialog. If you only need a prompt to let the user know some information, you can simply put a "I know" button, in fact, this button is a "cancel" action.

There is nothing to pay special attention to in the action button area. The only thing that can be thought of is that after Android 4.0, the left and right positions of "OK" and "canceled" are changed to "OK" on the right, "cancel" on the left. If you want to be alone with the mainstream, I think you can only respond with "Haha. After all, the term "user habits" exists. When everyone is used to a set of rules, the so-called "Paradox innovation" may be just a shield for "naughty.


Toast

Dialog is a severe pop-up box, which also describes the design philosophy of "content". If there is too little content, you just want to prompt the user, rather than asking the user to make a selection or decision, you can fully consider using a more lightweight Toast that has a small impact on the user experience. In user operations, Toast is more user-friendly than Dialog, because Toast will automatically disappear after a period of time (the default length of Android is 3.5 seconds, and the short value is 2 seconds, however, Dialog must be interfered by the user before it can disappear. At the same time, Toast does not affect the user's next operations on the interface, while Dialog is an interruption. If you do not perform any operations, Toast wants to perform the next operation. Believe it or not, if an application can pop up more than three Dialog consecutively, the user must uninstall the application instead of dropping the mobile phone.


Basic development and usage of Dialog


Android officially recommends that you do not directly use the Dialog class to construct the pop-up box of the application. In development practices, it is easy to find that it is not convenient to directly construct the pop-up box using Dialog, basic View frameworks all need to be designed and planned by themselves. For a simple pop-up box, the implementation complexity obviously does not meet development expectations. Following the official suggestions, we usually use AlertDialog to construct the pop-up box. At the same time, the Android official team has prepared for the selection window of dates and times that may occur during the development process, datePickerDialog and TimePickerDialog. (Recommended an open-source project, more user-friendly and beautiful https://github.com/flavienlaurent/datetimepicker)


In addition, you have to mention another Dialog provided by Android, namely ProgressDialog. This Dialog type is not officially recommended for Android. The original saying is: Avoid using ProgressDialog. From the perspective of development, ProgressDialog is extremely simple to use, and there is no high threshold. The Android official recommendation is more about design and user experience. The ProgressDialog pop-up takes a very small amount of space on the screen, and other areas are covered with gray masks. In general, ProgressDialog also needs to block the next operation of the user until the waiting event is completed. Even if possible device rotation is not taken into account, the single, blocking, and unfriendly view of ProgressDialog is sufficient to cause user discomfort. Therefore, we recommend that you embed the ProgressBar in the view layout instead of waiting for users during the design and development processes. The reasons include:

1. The screen is not covered with gray masks. I believe many users do not like such a thing;

2. ProgressBar does not block all operations on the screen. Even if the ProgressBar is displayed, the use of the NavigationDrawer control, for example, is not affected.

3. During Development, ProgressDialog is difficult to perform rotation. Therefore, it is prone to negligence, resulting in user confusion or misoperation.


The following describes how to use AlertDialog.

AlertDialog example:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),                AlertDialog.THEME_DEVICE_DEFAULT_DARK);        builder.setTitle("Dialog title")                .setIcon(android.R.drawable.stat_sys_warning)                .setMessage("Dialog content")                .setPositiveButton("OK", null)                .setNegativeButton("Cancel", null);        builder.create().show();

:


The pop-up window constructed by using AlertDialog is constructed by the Builder. Besides setting the Three Visual structures, you can also set whether the settings can be canceled (through the return button ). Two methods:

The first is called when AlertDialog. Builder is constructed.

setCancelable(boolean cancelable)
The second method is to call the same Dialog interface generated by AlertDialog. Builder create.

You can also set whether to make the pop-up box disappear when you click a view area other than the pop-up box, by calling the generated Dialog interface:

setCanceledOnTouchOutside(boolean cancel)

Both of the preceding values are false by default.


1. List to be displayed

Call the AlertDialog. Builder interface.

setAdapter(ListAdapter adapter, DialogInterface.OnClickListener listener)

The adapter parameter is the Adapter of the ListView to determine the view of the list.

The listener parameter is the click listener of the list item.


Visual effects include:

In this case, you do not need to click "OK" or "cancel". Simply click the list item to select it.


2. The radio list needs to be displayed.

Shape:


Implementation Code:

AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK);        builder.setTitle("Choose ringtone")                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        //Handle ok event                    }                })                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        //Handle cancel event                    }                })                .setSingleChoiceItems(ringtones, 0, new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        //Handle item click event                    }                });        builder.create().show();

AlertDialog. Builder's setSingleChoiceItems interface has four forms:

First:

setSingleChoiceItems(CharSequence[] items, int checkedItem, DialogInterface.OnClickListener listener)
The items parameter is a character displayed in the list;

Because the checkedItem list is single-choice, there is usually a selected item by default. this parameter is used to specify the items selected by default, starting from 0. If the value is-1, no default option is selected;

The listener parameter is the listener for clicking a list item.

This method is suitable for selecting simple characters.


Second:

setSingleChoiceItems(int itemsId, int checkedItem, DialogInterface.OnClickListener listener)
The itemsId parameter is a pre-defined String array in the specified xml. The meaning of other parameters is the same as that of the first one.


Third:

setSingleChoiceItems(ListAdapter adapter, int checkedItem, DialogInterface.OnClickListener listener)

The adapter parameter is the list Adapter, used to determine the visual effect of each list item

CheckedItem and listener have the same meaning as in the first method.

This method is suitable for the complex view requirements of options.


Fourth:

setSingleChoiceItems (Cursor cursor, int checkedItem, String labelColumn, DialogInterface.OnClickListener listener)

Cursor is the database of the project data in the list. Cursor

The labelColumn parameter is the name of the column of the data to be displayed in the database.

Other parameters are the same as those of the other three methods.


The question of whether the action button needs to be displayed in the single-choice pop-up box is raised again. We recommend that you display the "OK" and "cancel" buttons at the same time.

The reason for displaying the "OK" button is that, in actual use, users are very likely to take turns clicking different options. If the developer sees the option as "OK, in this way, the user needs to perform a lot of repeated actions. The user may have the following behavior:

1. Habitual movements of fingers;

2. If you want to directly view the result by selecting different options, such as changing the topic (if you want to see the direct effect after the change, you can choose to confirm the matching result ).


The reason why the "cancel" button is displayed is:

1. Because the pop-up box can cancel the settings by clicking the external area, it is assumed that you have used multiple applications that have different settings for the pop-up box, it is very likely that you have confused whether you can click the external area to cancel the pop-up box. Therefore, you can directly provide a "cancel" button to solve your concerns, as stated in the Android design specifications, users should not think about it, but provide the most direct options for users to choose. This is a good user experience.

2. Even if you can cancel the pop-up box by pressing the return button on your phone, the distance between the user's fingers and the Return key is not small in most cases, this may also result in a mobile phone slide, and the worst user experience is nothing more. Therefore, a "cancel" button is provided. In most cases, you can click "cancel" to cancel the pop-up box, which is more convenient and safer.


3. You need to display the multiple choice list

Shape:


The following code implements Dialog:

AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT);        builder.setTitle("Pick your toppings")                .setMultiChoiceItems(new String[]{"Onion", "Lettuce", "Tomato"},                new boolean[]{false, true, true},                new DialogInterface.OnMultiChoiceClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {                        //Handle item click event                    }                })                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        // Handle ok event                    }                })                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        // Handle cancel event                    }                });        builder.create().show();

AlertDIalog. Builder's setMultiChoiceItems method has three forms:


First:

setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)

The items parameter has the same meaning as the single-choice parameter. It is the character set combination of all items;

Which of the following are the default options for the checkedItems parameter. It should be noted that if it is null, it indicates that no default value is selected. If it is not null, the length must be the same as that of items.

The listener parameter is the project click listener in the table.


Second:

setMultiChoiceItems(int itemsId, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)

The itemsId parameter specifies all items to be displayed to the pre-defined String array. Other parameters are the same as the first one.


Third:

setMultiChoiceItems(Cursor cursor, String isCheckedColumn, String labelColumn, DialogInterface.OnMultiChoiceClickListener listener)

The cursor parameter is the database of the project to be displayed.

LabalColumn is the name of the column in the database where the project data is located.

Other parameters are the same as those of other methods.


It can be found that the pop-up box containing the multiple-choice list does not use the method constructed by specifying the Adapter, which seems to be missing. It is not difficult to find that there are few pop-up boxes for multiple options in a complex view. I personally don't think of any scenarios that require complex views and multiple options-the pop-up box. Of course, if you want to implement this kind of requirement, you can use the pop-up box of the custom view (which will be introduced later ).


4. View customization required


Custom View refers to the "content" area view of custom Dialog, which is implemented through API setView (View view. The implementation process is also very simple. You can design a set of LayoutInflater to generate a View and set the View. If necessary listening is required in this View ("content" Custom View), you can use the findViewById method to obtain the desired object and process it accordingly.


PS: do not set the Title for AlertDialog. Builder. The final Dialog will not have the Title view.


Dialog Development (advanced tutorial)


Through the above introduction, I believe that there should be no problem with the use of the Dialog at least view. Next, there are some issues that need to be addressed in the actual development process. For example, if the device is rotated, what will happen to the preceding Dialog? The answer is that they will disappear. Why does it disappear? Take the Activity most familiar with the development process as an example. If the device rotates, the Activity first destroys onDestroy and then restores onCreate. At the same time, the necessary data can be recovered through Bundle. However, the preceding Dialog cannot process the lifecycle of the device. Once the device is rotated, the system immediately dismiss it. By introducing DialogFragment, it can be used as the carrier of AlertDialog to solve this problem perfectly.


DialogFragment inherits from Fragment, which is used to carry the DialogFragment. Events such as device rotation DialogFragment naturally have the ability to handle them. The DialogFragment is not directly dismiss by the system.


It is very easy to implement a DialogFragment. You only need to implement the onCreateDialog method. Its prototype is:

public Dialog onCreateDialog(Bundle savedInstanceState) {        return new Dialog(getActivity(), getTheme());    }

You can directly return a Dialog object, so the first AlertDialog implemented above can be converted:

public Dialog onCreateDialog(Bundle savedInstanceState) {        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),                AlertDialog.THEME_DEVICE_DEFAULT_DARK);        builder.setTitle("Dialog title")                .setIcon(android.R.drawable.stat_sys_warning)                .setMessage("Dialog content")                .setPositiveButton("OK", null)                .setNegativeButton("Cancel", null);        return builder.create()    }
This way, the Dialog is not displayed. Like a normal Dialog, a show method is required to trigger the Dialog method. However, the show method of Dialog implemented by DialogFragment is somewhat different:

public void show(FragmentManager manager, String tag)public int show(FragmentTransaction transaction, String tag)

Do not forget that DialogFragment inherits from Fragment. to display it, FragmentManager or FragmentTransaction must be used. If DialogFragment is called in Fragment, getChildFragmentManager must be used during show. This ensures the correct Fragment hierarchy.

By introducing DialogFragment, The DialogFragment of the rotating device does not disappear. However, if the Dialog content has a status change, it will be reset after rotation. In fact, this problem is to solve the Fragment rotating screen problem. OnSaveInstanceState works well with onCreateDialog. I will not go into details here.

Finally, a strong prompt !!! To implement your own DialogFragment, you must retain the default constructor, which is an empty and public constructor. Otherwise, a program exception occurs.


Summary


This article describes how to use Dialog in Android from design to development. In essence, the use of Dialog is very simple, and more is about the application, product quality and user experience. Whether it's mobile internet or traditional enterprises, quality and user experience must keep pace with the times. ·


How can android custom dialog style be applied to its own dialog, key code is required

1. Create a CustomTheme. xml file under res/value.
Redefines a CustomDialogTheme Style, inherits the Theme. Dialog of the system, and then overwrites the "android: windowBackground" and "buttonStyle" attributes.
Define a CustomTheme Style, inherit the Theme topic of the system, and re-define the dialogTheme item in CustomTheme to specify it as the newly created CustomDialogTheme.
2. Under the application tag in Manifest, specify the "android: theme" attribute as the newly defined customeme
Bytes ----------------------------------------------------------------------------------------------
For more questions and answers, please go to @ Android Sina Weibo


How to Implement the mode DIalog in android

Two methods
1 service sends a broadcast intent message, and other activities register the receiver er. Toast
2 service sends an intent to an activity, which starts and displays a prompt.
This activity should not be full screen and should not be included in history records. Only serves as a prompt.

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.