Android Common dialog box use Daquan _android

Source: Internet
Author: User
Tags prepare versions

Everyday life we can be seen Everywhere dialog box, there are a lot of tips, more convenient to prompt users to do different operations.

One, two features of the dialog box and some common dialog boxes

1. When the pop-up dialog box is the end UI thread (that is, the main thread);

2. The current activity will lose focus;

3. Message dialog box, confirmation dialog box, List dialog box, radio and Multi-selection dialog box, custom dialog box

Second, the composition of the dialog box (generally there are four components)

1. Icon

2. Title

3. Content

4. Button

Three, then how to create a dialog box? (Four step composition)

1. The first step is to create the Alertdialog.builder object (Builder mode)

2. The second step is to set up areas such as icons, headings, content, and buttons

3. The third step calls the Create () method for creation (general automatic invocation)

4. The fourth step calls the show () method to display

Four, click the Jump interface and long Press pop-up dialog box business logic

1. Then the above learning ListView to achieve common operations, in daily life, we often chat QQ, in the chat list, but we click on a line, will enter the chat interface, when we are long in a row, will pop up and delete tips.

The 2.mainactivity.java code is as follows

Package Com.oldtogether.adapterdemo2;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import Android.app.AlertDialog;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.os.Bundle;
Import android.support.v7.app.ActionBarActivity;
Import Android.view.View;
Import Android.view.View.OnLongClickListener;
Import Android.widget.AdapterView;
Import Android.widget.AdapterView.OnItemClickListener;
Import Android.widget.AdapterView.OnItemLongClickListener;
Import Android.widget.ListView;
Import Android.widget.SimpleAdapter;

Import Android.widget.Toast; public class MainActivity4 extends Actionbaractivity implements Onitemclicklistener, Onitemlongclicklistener {//create array, mining Traverse private int[with a For loop] Imageids = new int[] {R.drawable.daxiang, R.drawable.maozi, R.drawable.nangua, R.drawable.nangu
 OBQ, R.drawable.tiaopi, R.drawable.xiaolian, R.drawable.xin, R.drawable.weixin, R.drawable.hongx, R.DRAWABLE.XM}; PRivate string[] titles = new string[] {"Sell Meng Elephant", "Christmas Hat", "Angry Pumpkin", "sad expression", "Naughty expression", "My Qian smiley face", "Oldtogether Love", "Micro Letter", "Pink Girl Heart"
 , "a generation of masturbate"}; Private string[] versions = new string[] {"Version: 1.10", "Version: 2.10", "Version: 1.11", "Version: 2.12", "Version: 3.10", "Version: 2.20", "Version: 5.20", "
 Version: 1.23 "," Version: 2.21 "," Version: 2.40 ",}; Private string[] sizes = new string[] {"Size: 32.01M", "Size: 32.02M", "Size: 23.01M", "Size: 11.01M", "Size: 41.01M", "Size: 11.01M", "size

 : 33.01M ", Size: 33.01M", "Size: 33.01M", "Size: 33.01M",};
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

 Setcontentview (R.layout.listview);
 1, the ListView object ListView LV = (ListView) Findviewbyid (R.id.lv_play);
 2, data source list<map<string, object>> List = new arraylist<map<string, object>> ();
 for (int i = 0; i < titles.length i++) {map<string, object> Map = new hashmap<string, object> ();
 Map.put ("logo", imageids[i]);
 Map.put ("title", Titles[i]);
 Map.put ("Version", Versions[i]); Map. put ("size", sizes[i]);
 List.add (map);
 }//3, set adapter MyAdapter3 Adapter3 = new MyAdapter3 (this);
 Adapter3.setlist (list)//Incoming data//4, Association adapter lv.setadapter (ADAPTER3);
 5. Set up event listeners for ListView (two common events), let the main MainActivity2 implement the interface, and rewrite the method Lv.setonitemclicklistener (this);
 Lv.setonitemlongclicklistener (this); @Override public void Onitemclick (adapterview<?> parent, view view, int position, long ID) {/* Creates an intent object that calls the SE
 The Tclass method indicates that "the activity is invoked in that activity," the secondary intention/Intent Intent = new Intent ();

 Intent.setclass (Getapplicationcontext (), detailactivity.class); Get the data for the click Line HashMap <String,Object> itemmap= (hashmap<string,object>) parent.getitematposition (position)
 ;
 Intent.putextra ("index", "" "+position);//Get number Intent.putextra (" title "," "+itemmap.get (" title "))//Get title
 StartActivity (Intent); @Override public boolean Onitemlongclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {Alertdialog.bu
 Ilder builder=new Alertdialog.builder (this); Builder.seticon (r.drAwable.ic_launcher);
 Builder.settitle ("message hint");
 Builder.setmessage ("This is a simple title"); Builder.setpositivebutton (OK), new Dialoginterface.onclicklistener () {@Override public void OnClick (dialoginterface dialog, int which) {//Click the OK button in the dialog box to appear with a Toast hint box toast.maketext (mainactivity4.this, "Click OK", Toast.length_long). Show ()
 ;
 }
 });
 Builder.create (). Show ();
 return true;

 * * The return value represents the digest of the event 1, true: to digest the event, the event will not continue to pass 2, false: Indicates that the event does not digest, the event continues to pass * conclusion: If you want to have a long press event and no Click event occurs, set the return value to True

3. Code concise "Point of contact"

1. Obtain the Builder object through the creator mode, and then call its method by means of a dot to simplify the code;

2. The principle of using a point is that the returned value of the method being invoked is the current object itself;

3. The following is code that implements this same functionality through a dot in a long method.

@Override Public
 Boolean Onitemlongclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {
 new ALERTDI Alog. Builder (This)
 . SetIcon (r.drawable.ic_launcher).
 settitle ("message Prompt")
 . Setmessage ("This is a simple title")
 . Setpositivebutton (OK), new Dialoginterface.onclicklistener () {

 @Override public
 void OnClick ( Dialoginterface dialog, int which) {
 toast.maketext (Mainactivity4.this, "clicked OK", Toast.length_long). Show ();
 })
 . Show ();
 return true;
 }

4. Operating Results



Five, the above is the message dialog box implementation, again immediately after the Learning confirmation dialog box

1. The confirmation dialog that can be seen everywhere, uses: often used for some user to decide the operation, such as exit data, delete data, confirm payment, etc.

2. Direct Labeling Code

Package Com.oldtogether.adapterdemo2;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import Android.app.AlertDialog;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.os.Bundle;
Import android.support.v7.app.ActionBarActivity;
Import Android.view.View;
Import Android.view.View.OnLongClickListener;
Import Android.widget.AdapterView;
Import Android.widget.AdapterView.OnItemClickListener;
Import Android.widget.AdapterView.OnItemLongClickListener;
Import Android.widget.ListView;
Import Android.widget.SimpleAdapter;

Import Android.widget.Toast; public class MainActivity4 extends Actionbaractivity implements Onitemclicklistener, Onitemlongclicklistener {//create array, mining Traverse private int[with a For loop] Imageids = new int[] {R.drawable.daxiang, R.drawable.maozi, R.drawable.nangua, R.drawable.nangu
 OBQ, R.drawable.tiaopi, R.drawable.xiaolian, R.drawable.xin, R.drawable.weixin, R.drawable.hongx, R.DRAWABLE.XM}; PRivate string[] titles = new string[] {"Sell Meng Elephant", "Christmas Hat", "Angry Pumpkin", "sad expression", "Naughty expression", "My Qian smiley face", "Oldtogether Love", "Micro Letter", "Pink Girl Heart"
 , "a generation of masturbate"}; Private string[] versions = new string[] {"Version: 1.10", "Version: 2.10", "Version: 1.11", "Version: 2.12", "Version: 3.10", "Version: 2.20", "Version: 5.20", "
 Version: 1.23 "," Version: 2.21 "," Version: 2.40 ",}; Private string[] sizes = new string[] {"Size: 32.01M", "Size: 32.02M", "Size: 23.01M", "Size: 11.01M", "Size: 41.01M", "Size: 11.01M", "size

 : 33.01M ", Size: 33.01M", "Size: 33.01M", "Size: 33.01M",};
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

 Setcontentview (R.layout.listview);
 1, the ListView object ListView LV = (ListView) Findviewbyid (R.id.lv_play);
 2, data source list<map<string, object>> List = new arraylist<map<string, object>> ();
 for (int i = 0; i < titles.length i++) {map<string, object> Map = new hashmap<string, object> ();
 Map.put ("logo", imageids[i]);
 Map.put ("title", Titles[i]);
 Map.put ("Version", Versions[i]); Map. put ("size", sizes[i]);
 List.add (map);
 }//3, set adapter MyAdapter3 Adapter3 = new MyAdapter3 (this);
 Adapter3.setlist (list)//Incoming data//4, Association adapter lv.setadapter (ADAPTER3);
 5. Set up event listeners for ListView (two common events), let the main MainActivity2 implement the interface, and rewrite the method Lv.setonitemclicklistener (this);
 Lv.setonitemlongclicklistener (this); @Override public void Onitemclick (adapterview<?> parent, view view, int position, long ID) {/* Creates an intent object that calls the SE
 The Tclass method indicates that "the activity is invoked in that activity," the secondary intention/Intent Intent = new Intent ();

 Intent.setclass (Getapplicationcontext (), detailactivity.class); Get the data for the click Line HashMap <String,Object> itemmap= (hashmap<string,object>) parent.getitematposition (position)
 ;
 Intent.putextra ("index", "" "+position);//Get number Intent.putextra (" title "," "+itemmap.get (" title "))//Get title
 StartActivity (Intent); @Override public boolean Onitemlongclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {//Long Click OK dialog box NE W Alertdialog.builder (This). SetIcon (r.drawable.ic_launcher). SETtitle ("Are you sure you want to quit?") "). Setnegativebutton (" Cancel ", null)//null, which describes any operation that is not customized, simply closes the current dialog box and stops at the original interface. Setpositivebutton (OK), new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {finish ();//Close the current
 Activity}}). Show ();
 return true;

 }
}

3. Operating Results

4. Add: When clicking Cancel is going to stay in the current activity; When click OK will exit the current activity, return to the emulator main interface.

Six, List dialog box

1. Use: Display the data in the form of a list, list item clickable, need an array resource as the data source.

2. Core method: Setitems (); In preparing an array resource;

3. The code is as follows:

Package Com.oldtogether.adapterdemo2;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import Android.app.AlertDialog;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.os.Bundle;
Import android.support.v7.app.ActionBarActivity;
Import Android.view.View;
Import Android.view.View.OnLongClickListener;
Import Android.widget.AdapterView;
Import Android.widget.AdapterView.OnItemClickListener;
Import Android.widget.AdapterView.OnItemLongClickListener;
Import Android.widget.ListView;
Import Android.widget.SimpleAdapter;

Import Android.widget.Toast; public class MainActivity4 extends Actionbaractivity implements Onitemclicklistener, Onitemlongclicklistener {//create array, mining Traverse private int[with a For loop] Imageids = new int[] {R.drawable.daxiang, R.drawable.maozi, R.drawable.nangua, R.drawable.nangu
 OBQ, R.drawable.tiaopi, R.drawable.xiaolian, R.drawable.xin, R.drawable.weixin, R.drawable.hongx, R.DRAWABLE.XM}; PRivate string[] titles = new string[] {"Sell Meng Elephant", "Christmas Hat", "Angry Pumpkin", "sad expression", "Naughty expression", "My Qian smiley face", "Oldtogether Love", "Micro Letter", "Pink Girl Heart"
 , "a generation of masturbate"}; Private string[] versions = new string[] {"Version: 1.10", "Version: 2.10", "Version: 1.11", "Version: 2.12", "Version: 3.10", "Version: 2.20", "Version: 5.20", "
 Version: 1.23 "," Version: 2.21 "," Version: 2.40 ",}; Private string[] sizes = new string[] {"Size: 32.01M", "Size: 32.02M", "Size: 23.01M", "Size: 11.01M", "Size: 41.01M", "Size: 11.01M", "size

 : 33.01M ", Size: 33.01M", "Size: 33.01M", "Size: 33.01M",};
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

 Setcontentview (R.layout.listview);
 1, the ListView object ListView LV = (ListView) Findviewbyid (R.id.lv_play);
 2, data source list<map<string, object>> List = new arraylist<map<string, object>> ();
 for (int i = 0; i < titles.length i++) {map<string, object> Map = new hashmap<string, object> ();
 Map.put ("logo", imageids[i]);
 Map.put ("title", Titles[i]);
 Map.put ("Version", Versions[i]); Map. put ("size", sizes[i]);
 List.add (map);
 }//3, set adapter MyAdapter3 Adapter3 = new MyAdapter3 (this);
 Adapter3.setlist (list)//Incoming data//4, Association adapter lv.setadapter (ADAPTER3);
 5. Set up event listeners for ListView (two common events), let the main MainActivity2 implement the interface, and rewrite the method Lv.setonitemclicklistener (this);
 Lv.setonitemlongclicklistener (this); @Override public void Onitemclick (adapterview<?> parent, view view, int position, long ID) {/* Creates an intent object that calls the SE
 The Tclass method indicates that "the activity is invoked in that activity," the secondary intention/Intent Intent = new Intent ();

 Intent.setclass (Getapplicationcontext (), detailactivity.class); Get the data for the click Line HashMap <String,Object> itemmap= (hashmap<string,object>) parent.getitematposition (position)
 ;
 Intent.putextra ("index", "" "+position);//Get number Intent.putextra (" title "," "+itemmap.get (" title "))//Get title
 StartActivity (Intent);  @Override public boolean Onitemlongclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {//List dialog final String [] sites={"Print shop", "Boy's Apartment", "Girl's Apartment", "Halal canteen", "Public canteen", "library", "Bath Center"};The reason for setting to final (constant) is that you can penetrate the scope new Alertdialog.builder (this). Settitle ("Lanzhou City College Pui Li Campus"). Setitems (Sites, new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {//parameter which represents the message
 The first few items in the dialog box Toast.maketext (Mainactivity4.this, "You have selected +sites[which], Toast.length_long). Show (); }). Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface D
 Ialog, int which) {//close the second way of the dialog box, overriding a null method without any logic}}). Show ();
 return true;

 }
}

4. Operating Results


Seven, the Radio dialog box

1. Radio dialog box, use: Users need to make a single choice is to use; Core method: Setsinglechoiceitems ();

2. Implementation steps

1. Prepare an array resource (generally set to a constant array for easy penetration of the scope);

2. Call Setsinglechioceitems () to set the Radio list item.

3. Code implementation (write dialog related code directly in Onitemlongclick, other code)

The global variable 1 in the main class, the rating level selected by the staging user, and (in addition, if the initial value of this variable is set to 0, direct click to determine a 1 star score, there is a bug) 2, convenient penetration scope; int selectedid =-1; @Override public boolean Onitemlongclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {//Long pressed Radio dialog box final String [] stars={"1 Stars", "2 Stars", "2 Stars", "3 Stars", "4 Stars", "5 stars"};//are set to final (constant) because they can penetrate scope new Alertdialog.builder (this). Settitle (" Big Brother, a 5-Star score! "). Setsinglechoiceitems (Stars,-1, New Dialoginterface.onclicklistener () {/* * The first parameter: the array of resources to display; * Second argument: Default in the list of Radio dialog boxes The reason for the selected row mark (set to-1) is that the array defaults first subscript starting from 0, if you set this parameter to 0, the default will be 1 stars, with bugs, when you jump out of the Radio dialog box; * Third parameter: Click on a line event to customize the business logic code (this is done with simple toast)
 ; * Add: Dialog.dismiss () Let the dialog box disappear. * * @Override public void OnClick (Dialoginterface dialog, int which) {Selectedid = which;//plays a temporary role in the user's single selection, facilitating certainty that it is referenced to
 Ast.maketext (Mainactivity4.this, "You have selected now:" +stars[which], Toast.length_long). Show (); }). Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface D Ialog, int which) {Toast.maketext (Mainactivity4.this, "Your final decision is: "+stars[selectedid", Toast.length_long). Show (); }). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface D
 Ialog, int which) {//Null action Method}}). Show ();
 return true;

 }

4. Operating Results



Eight, multiple selection dialog box

1. Multi-selection dialog box. Uses: Provides the user to carry on the multiple choice; the Core method Setmultichoiceitems (); (Multi: Many meanings in English)

2. Implementation steps

1. Prepare an array resource;

2. Call the Setmultichoiceitems () method to set the list of multiple options;

3. Code implementation (the same way directly paste Onitemlongclick () method code)

arraylist<integer> choice = new arraylist<> ();//Create a ArrayList option to save in the dialog, set as global variable to penetrate scope @ Override public boolean Onitemlongclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {//Long pressed Multiple Marquee dialog box final String [] interests={"reading", "playing basketball", "big lol", "listening to music", "watching a movie", "Running"};//is set to final (constant) because it can penetrate scope new Alertdialog.builder (this). SetIcon (R.drawable.ic_launcher). Settitle ("What is your hobby?"  
 ") * * Setmultichoiceitems () three parameters * First parameter: resource array; * The second parameter: the default initial value, which is set to a Boolean array because it is multiple selections; * Third parameter: Click event for multiple marquee; * */Setmultichoiceitems (interests, new Boolean []{false,false,false,false,false,false}, New dialoginterface.onmultic  Hoiceclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which, Boolean ischecked) {/* * First parameter: Dialog object; * Second parameter: The item selected by the user in the Multiple-selection dialog box; * Third parameter: Whether checked, True is selected, False is not selected *//checked to add, regret is also can remove if (ischec
  ked) {choice.add (which);
  }else{Choice.remove (which); Toast.maketext (Mainactivity4.this, "Your current selection is:"+choice.tostring (), Toast.length_long). Show (); }). Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface D
 Ialog, int which) {Toast.maketext (Mainactivity4.this, "Your final decision is:" +choice.tostring (), Toast.length_long). Show ();
 }). Setnegativebutton ("Cancel", null). Show ();
 return true;

 }
}

4. Operating Results


Ix. Summary of Experience

1. Refer to the dialog box can be directly to the brain to fill out the composition of the dialogue, and Create dialog box steps;

2. When setting the default initial value in the Radio dialog box, "1" is used skillfully, the key point is the array subscript starting from 0, easy to appear bugs;

3. Two ways to close the dialog box (when clicking the Negative button). The first one: Add a redo to the second argument in the secondary method without any logical code click events; the second: set the second parameter directly to NULL;

4. Two classic penetrating scopes (incidental to magic and physical damage). The first time when defining a data resource, the array resource is final decorated with a constant that is convenient to invoke in other methods, that is, penetrating the scope; the second time when you create a radio and multiple-selection dialog box, In the Setsinglechioceitems () and Setmultichoiceitems () methods, sometimes the user may modify the first selection, while the secondary selection temporarily exists in the member variable of the outermost class (here int Selectedid and generic ArrayList object), easy to click on the OK button that calls the OnClick method is exploited and again penetrates the scope;

5. In short, daily life in a variety of common dialog boxes, reasonable use of dialog box will be better to achieve the interface between the user and communication.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.