In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail the example analysis of Android dialog box AlertDialog for you. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
AlertDialog can display a dialog box on the current interface, which is on top of all interface elements and can block the interaction ability of other controls, so AlertDialog is generally used to prompt some very important content or warnings.
1. Create AlertDialog
First, let's take a look at the general order in which AlertDialog is created. Unlike controls such as TextView and Button, AlertDialog does not call various methods directly after initialization (findViewById). If you think about the usage scenario of AlertDialog, it is not usually fixed to the interface like TextView and Button controls, but will only be triggered at a certain time (such as when the user clicks a button or is disconnected). So AlertDialog does not need to be created in a layout file, but instead constructs titles, icons, buttons, and so on, through an AlertDialog.Builder in the code.
1. Create an object for the constructor AlertDialog.Builder
two。 The title, information and icon of the dialog box are constructed by calling setTitle, setMessage, setIcon and other methods through the constructor object.
3. Call the setPositive/Negative/NeutralButton () method to set the positive button, negative button and neutral button as needed
4. Create an AlertDialog object by calling the create method of the constructor object
The 5.AlertDialog object calls the show method to make the dialog box appear on the interface.
Note: AlertDialog.Builder itself has a show method that displays dialog boxes, so steps 4 and 5 above can be simplified to one step.
Next, let's create a few commonly used AlertDialog. Create a new project, place five buttons on the activity_main.xml layout file, and click the button and the corresponding dialog box will pop up.
1.1the layout file code is as follows: 1.2 the main code of MainActivity is as follows: package com.fd.alertdialog; import android.content.DialogInterface;import android.os.Bundle;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import java.util.ArrayList Import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener {public static String TAG = MainActivity.class.getSimpleName (); private int chedkedItem = 0; private String name; private String pwd; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); bindView () } private void bindView () {Button btn_normal_dialog = (Button) findViewById (R.id.btn_normal_dialog); Button btn_item_dialog = (Button) findViewById (R.id.btn_item_dialog); Button btn_single_choice = (Button) findViewById (R.id.btn_single_choice); Button btn_multi_choice = (Button) findViewById (R.id.btn_multi_choice) Button btn_custom_dialog = (Button) findViewById (R.id.btn_custom_dialog); btn_normal_dialog.setOnClickListener (this); btn_item_dialog.setOnClickListener (this); btn_single_choice.setOnClickListener (this); btn_multi_choice.setOnClickListener (this); btn_custom_dialog.setOnClickListener (this) } @ Override public void onClick (View v) {switch (v.getId ()) {case R.id.btn_normal_dialog: tipDialog (); / / prompt dialog box break; case R.id.btn_item_dialog: itemListDialog () / / list dialog break; case R.id.btn_single_choice: singleChoiceDialog (); / / Radio dialog box break; case R.id.btn_multi_choice: multiChoiceDialog (); / / multiple selection dialog box break Case R.id.btn_custom_dialog: customDialog (); / / Custom dialog box break; default: break;}}
The code is relatively simple, so I won't explain it in detail here. Next, take a look at the specific code of each dialog box.
two。 General prompt dialog box
The prompt dialog box should be the most common AlertDialog, with the prompt title, message body, and buttons such as "cancel" and "OK" at the bottom.
/ * prompt dialog box * / public void tipDialog () {AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this); builder.setTitle ("prompt:"); builder.setMessage ("this is a normal dialog box,"); builder.setIcon (R.mipmap.ic_launcher); builder.setCancelable (true) / / Click the area outside the dialog box to make the dialog box disappear / / set the front button builder.setPositiveButton ("OK", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {Toast.makeText (MainActivity.this, "you clicked OK", Toast.LENGTH_SHORT). Show (); dialog.dismiss () }}); / / set the reverse button builder.setNegativeButton ("cancel", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {Toast.makeText (MainActivity.this, "you clicked cancel", Toast.LENGTH_SHORT). Show (); dialog.dismiss ();}}) / / set neutral button builder.setNeutralButton ("secrecy", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {Toast.makeText (MainActivity.this, "you chose neutrality", Toast.LENGTH_SHORT). Show (); dialog.dismiss ();}}); AlertDialog dialog = builder.create () / / create an AlertDialog object / / the listening event dialog.setOnShowListener displayed in the dialog box (new DialogInterface.OnShowListener () {@ Override public void onShow (DialogInterface dialog) {Log.e (TAG, "dialog shows");}}) / / listening event dialog.setOnCancelListener (new DialogInterface.OnCancelListener () {@ Override public void onCancel (DialogInterface dialog) {Log.e (TAG, "dialog disappears";}}); dialog.show (); / / Show dialog box}
Let's introduce the methods used in detail:
-setTitle: sets the title of the dialog box, such as "prompt", "warning", etc.
-setMessage: set the specific information to be conveyed by the dialog box
-setIcon: sets the icon of the dialog box
-setCancelable: click on the area outside the dialog box to make the dialog box disappear. Default is true.
-setPositiveButton: set the front button to mean "positive" and "confirm". The first parameter is the text displayed on the button, same as below.
-setNegativeButton: set the reverse button to indicate "negative", "deny" and "cancel"
-setNeutralButton: set the neutral button
-setOnShowListener: events triggered when the dialog box is displayed
-setOnCancelListener: the event triggered when the dialog box disappears.
Of course, these settings are not necessary, but according to your own needs. For example, titles and icons can be taken or not.
The effect is shown in the following figure:
You may have this question: since we wrote the text of the buttons at the bottom and the contents of the click events ourselves, isn't it possible to interchange the contents of the front buttons with the contents of the negative buttons? If you look at the running picture, you will find that the negative button is on the left side of the front button, so considering the user's operating habits and the semantics of the code, we'd better write according to API.
3. Normal list dialog box
The content of the list dialog box is a list of display contents, which requires the setItems method of the constructor. The first parameter is the list data, and the second parameter is the click listening interface. We want to achieve such a small function that when the user clicks on an item, a Toast prompts the contents of the selected item.
The code is as follows:
/ * list dialog box * / private void itemListDialog () {AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this); builder.setTitle ("choose your favorite course:"); builder.setCancelable (true); final String [] lesson = new String [] {"Chinese", "Mathematics", "English", "Chemistry", "Biology", "Physics", "physical Education"} Builder.setIcon (R.mipmap.ic_launcher); builder.setIcon (R.mipmap.tab_better_pressed) .setItems (lesson, new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {Toast.makeText (getApplicationContext (), "you chose" + lesson [which], Toast.LENGTH_SHORT). Show () }}) .create (); / / set the front button builder.setPositiveButton (OK, new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {dialog.dismiss ();}}) / / set the reverse button builder.setNegativeButton ("cancel", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {dialog.dismiss ();}}); AlertDialog dialog = builder.create (); / / create AlertDialog object dialog.show (); / / Show dialog box}
The effect of running is as follows:
4. Radio dialog box
The content of the radio dialog box is a single selection list, need to use the setSingleChoiceItems method, parameter 1 is the list data, parameter 2 is the default selected item, parameter 3 is the click listening interface, we want to achieve such a small function, the user will write down the selection after selecting a certain item, and select it by default the next time you click on the dialog box.
/ * Radio dialog box * / public void singleChoiceDialog () {AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this); builder.setTitle ("where you live now:"); final String [] cities = {"Beijing", "Shanghai", "Guangzhou", "Shenzhen", "Hangzhou", "Tianjin", "Chengdu"} Builder.setSingleChoiceItems (cities, chedkedItem, new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {Toast.makeText (getApplicationContext (), "you chose" + cities [which], Toast.LENGTH_SHORT) .show (); chedkedItem = which;}}) Builder.setPositiveButton ("confirm", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {dialog.dismiss ();}}); builder.setNegativeButton ("cancel", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {dialog.dismiss ();}}) AlertDialog dialog = builder.create (); / / create AlertDialog object dialog.show (); / / Show dialog box}
The effect of running is as follows:
You might put the checkedItem assignment in the click event of the confirm button, which seems fine at first glance, but it's wrong! Read Google's API documentation carefully to know that the setSingleChoiceItems method to achieve the onClick method which represents the currently selected list of item subscript, while setPositiveButton and setNegativeButton method where the which represents the type of button, the front button in the which value is-1, the reverse button is-2, and the list of item is not related.
There is a problem with the method of saving the selected item in the example. When the Activity is destroyed and recreated, the data will be lost. If you want to persist, use sharedpreferences or database.
5. Check dialog box
The check dialog box is a list that can be selected repeatedly, similar to the radio dialog box, except that the setMultiChoiceItems method is called and a Boolean parameter isChecked is added to indicate whether the currently clicked item is selected.
We create a collection, add the selected item to the collection, uncheck it, remove it from the collection, and click the confirm button to display the selected content.
/ * check box * / public void multiChoiceDialog () {AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this); builder.setTitle ("Please choose your favorite color:"); final String [] colors = {"red", "orange", "yellow", "green", "blue", "indigo", "purple"}; final List myColors = new ArrayList () Builder.setMultiChoiceItems (colors, null, new DialogInterface.OnMultiChoiceClickListener () {@ Override public void onClick (DialogInterface dialog, int which, boolean isChecked) {if (isChecked) {myColors.add (colors [which]);} else {myColors.remove (colors [which]);}) Builder.setPositiveButton ("confirm", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {String result = "; for (String color: myColors) {result + = color +", ";} Toast.makeText (getApplicationContext ()," you chose: "+ result, Toast.LENGTH_SHORT). Show () Dialog.dismiss ();}}); builder.setNegativeButton ("cancel", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {myColors.clear (); dialog.dismiss ();}}); AlertDialog dialog = builder.create (); / / create AlertDialog object dialog.show () / / Show dialog box}
The effect after running is as follows:
6. Customize login dialog box
Sometimes, just displaying a simple title and information will not meet our requirements, for example, if we want to implement a login dialog box, we need to place an EditText input box on the dialog box. AlertDialog has already prepared the setView method for us, just put the View object of the dialog box we need.
6.1 customize the layout file of the login dialog box 6.2 Code logic of the custom dialog box
The setView method is called through the AlertDialog object, so the code order here is slightly different: we create the AlertDialog object and the View object before initializing the controls in the dialog box.
/ * Custom login dialog box * / public void customDialog () {AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this); final AlertDialog dialog = builder.create (); View dialogView = View.inflate (MainActivity.this, R.layout.activity_custom, null); dialog.setView (dialogView); dialog.show (); final EditText et_name = dialogView.findViewById (R.id.et_name) Final EditText et_pwd = dialogView.findViewById (R.id.et_pwd); final Button btn_login = dialogView.findViewById (R.id.btn_login); final Button btn_cancel = dialogView.findViewById (R.id.btn_cancel); btn_login.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View view) {name = et_name.getText () .toString () Pwd = et_pwd.getText (). ToString (); if (TextUtils.isEmpty (name) | | TextUtils.isEmpty (pwd)) {Toast.makeText (MainActivity.this, "username or password cannot be empty!", Toast.LENGTH_SHORT) .show (); return } Toast.makeText (MainActivity.this, "user name:" + name + "\ n" + "user password:" + pwd, Toast.LENGTH_SHORT). Show (); dialog.dismiss ();}}); btn_cancel.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View view) {dialog.dismiss ()) });}
The effect of the run is as follows:
7. Custom dialog box needs to pay attention to the width of 7.1 system dialog
The default is fixed, even if you customize the layout how to modify the width does not work, the height can be automatically adjusted according to the layout. If you want to change the pop-up form size, you can use the following code to change the width and height of the dialog box. This code must be called after the dialog.show () method to be valid.
/ / set the location form size here, dialog.getWindow () .setLayout (width,height)
Create a new layout file activity_layout.xml
The code logic is similar to the code logic of 6.2, except that there are more calls to set the dialog width.
/ * modify the width of the dialog box display * / public void customDialogDisplay () {AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this); final AlertDialog dialog = builder.create (); View dialogView = View.inflate (MainActivity.this, R.layout.activity_layout, null); dialog.setView (dialogView); dialog.show (); dialog.getWindow () .setLayout (ScreenUtils.getScreenWidth (this) / 4x3, LinearLayout.LayoutParams.WRAP_CONTENT) Final EditText et_name = dialogView.findViewById (R.id.et_name); final EditText et_pwd = dialogView.findViewById (R.id.et_pwd); final Button btn_login = dialogView.findViewById (R.id.btn_login); final Button btn_cancel = dialogView.findViewById (R.id.btn_cancel) Btn_login.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View view) {name = et_name.getText () .toString (); pwd = et_pwd.getText () .toString ()) If (TextUtils.isEmpty (name) | | TextUtils.isEmpty (pwd)) {Toast.makeText (MainActivity.this, "username or password cannot be empty!", Toast.LENGTH_SHORT) .show (); return } Toast.makeText (MainActivity.this, "user name:" + name + "\ n" + "user password:" + pwd, Toast.LENGTH_SHORT). Show (); dialog.dismiss ();}}); btn_cancel.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View view) {dialog.dismiss ()) });}
ScreenUtils tool class code
Public class ScreenUtils {/ * get screen height (px) * / public static int getScreenHeight (Context context) {return context.getResources () .getDisplayMetrics () .heightPixels;} / * * get screen width (px) * / public static int getScreenWidth (Context context) {return context.getResources () .getDisplayMetrics () .widthPixels;}
Effect picture:
7.2 change the brightness of the Activity background after Android Dialog pop-up:
Modify the .lp.alpha size in the code, and the value can be set according to your own requirements.
/ / set screen background to darken private void setScreenBgDarken () {WindowManager.LayoutParams lp = getWindow (). GetAttributes (); lp.alpha = 0.5f; lp.dimAmount = 0.5f; getWindow (). SetAttributes (lp);} / / set screen background to brighten private void setScreenBgLight () {WindowManager.LayoutParams lp = getWindow (). GetAttributes (); lp.alpha = 1.0f; lp.dimAmount = 1.0f; getWindow (). SetAttributes (lp) } 7.3 how to control the position of the pop-up window:
The default usually pops up in the middle of the screen, but you can also control it to pop up from somewhere else, such as from the bottom.
Private void popFromBottom (Dialog dialog) {Window win = dialog.getWindow (); win.setGravity (Gravity.BOTTOM); / / here controls the pop-up position win.getDecorView (). SetPadding (0,0,0,0); WindowManager.LayoutParams lp = win.getAttributes (); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; dialog.getWindow (). SetBackgroundDrawable (null); win.setAttributes (lp) } this is the end of the article on "sample Analysis of Android Dialog AlertDialog". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.