Use of Android Common instance-alert dialog

Source: Internet
Author: User
Tags getmessage

Use of Android Common instance-alert dialog

The use of Alertdialog is common, and in applications where you want users to make "yes" or "no" or a variety of other choices, you can use Alertdialog to maintain the same activity and not change the user's screen.

This article mainly explains how to achieve a variety of alertdialog, the article is longer, if you can read it carefully, the various usages of alertdialog should be able to grasp, the following is the final effect we want to achieve today:

At first glance, in the application we have seen a lot of strange dialog box, but careful analysis, it still has rules to follow, there are only a few, we have to learn from the simple, cobwebs to grasp a seemingly complex function. As long as we clear the basic logic, the other needs of the appropriate transformation can be used for us!
the basic structure of Alertdialog is as follows :

可以将对话框主要分为三个部分:上面区域是标题栏和图标,中间区域是内容区,下方是button区;其他形式各异的对话框也都是基于此的变体而已!

So to create a dialog box, we need to do something:

1, you first need to create a Alertdialog.builder object, the basic syntax:

AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(this);

2, after creating the Alertdialogbuilder object, you can construct a dialog box by calling its create () method

AlertDialog alertDialog = alertDialogBuilder.create();alertDialog.show();//将dialog显示出来

3, but we still have a question, how to set the other properties of dialog, that is, how to control the title, chart area, content area and button area, we naturally think of a series of set methods; Implemented by invoking the Setxx method of the Alertdialogbuilder object:

alertDialogBuilder.setTitle();//设置标题alertDialogBuilder.setIcon();//设置图表/*设置下方按钮*/alertDialogBuilder.setPositiveButton();alertDialogBuilder.setNegativeButton();alertDialogBuilder.setNeutralButton();/*对话框内容区域的设置提供了多种方法*/setMessage();//设置显示文本setItems();//设置对话框内容为简单列表项setSingleChoiceItems();//设置对话框内容为单选列表项setMultiChoiceItems();//设置对话框内容为多选列表项setAdapter();//设置对话框内容为自定义列表项setView();//设置对话框内容为自定义View//设置对话框是否可取消setCancelable(booleab cancelable);setCancelListener(onCancelListener);

Comprehensive: The use of alertdialog in fact is mainly for how to set up content area;

下面我们通过使用不同的内容区域的设置方法,实现几个常用的对话框;基本思路是在MainActivity中添加几个Button,点击后分别弹出对应的AlertDialog

steps:
- 1 . Create Android project-> "Alertdialogdemo"
- 2 . Writing Activity_main.xml layout files
- 3. Write the required Strings.xml
- 4. Writing Methods in Mainactivity

Limited to the length of the problem, now only put the key part of the code, the rest of the reader to implement their own;
activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:orientation=" vertical "android:layout_width=" match_parent "Android:layout_ height= "Match_parent" ><button android:id= "@+id/btn_simple_dialog" android:text= "@string/simple_dialog" and    Roid:textcolor= "#ffffff" android:textsize= "18sp" android:background= "#449F1D" android:layout_margintop= "10DP" android:layout_marginleft= "50DP" android:layout_marginright= "50DP" android:layout_width= "Match_parent" Android:la yout_height= "Wrap_content"/><button android:id= "@+id/btn_simple_list_dialog" android:text= "@string/simple_ List_dialog "android:textcolor=" #ffffff "android:textsize=" 18sp "android:background=" #449F1D "android:layout_m argintop= "10DP" android:layout_marginleft= "50DP" android:layout_marginright= "50DP" android:layout_width= "Match_pa Rent "android:layout_height=" wrap_content "/><button AndroId:id= "@+id/btn_single_choice_dialog" android:text= "@string/single_choice_dialog" android:textcolor= "#ffffff" and Roid:textsize= "18SP" android:background= "#449F1D" android:layout_margintop= "10DP" android:layout_marginleft= "50DP "Android:layout_marginright=" 50DP "android:layout_width=" match_parent "android:layout_height=" Wrap_content "/&gt ; <button android:id= "@+id/btn_multi_choice_dialog" android:text= "@string/multi_choice_dialog" Android:textColo R= "#ffffff" android:textsize= "18sp" android:background= "#449F1D" android:layout_margintop= "10DP" android:layou t_marginleft= "50DP" android:layout_marginright= "50DP" android:layout_width= "Match_parent" android:layout_height= " Wrap_content "/><button android:id=" @+id/btn_custom_adapter_dialog "android:text=" @string/custom_adapter_ Dialog "android:textcolor=" #ffffff "android:textsize=" 18sp "android:background=" #449F1D "Android:layout_margin top= "10DP" Android:layout_marginleft= "50DP" android:layout_marginright= "50DP" android:layout_width= "match_parent" android:layout_height= "WR Ap_content "/><button android:id=" @+id/btn_custom_view_dialog "android:text=" @string/custom_view_dialog "an    Droid:textcolor= "#ffffff" android:textsize= "18sp" android:background= "#449F1D" android:layout_margintop= "10DP" android:layout_marginleft= "50DP" android:layout_marginright= "50DP" android:layout_width= "Match_parent" android:l ayout_height= "Wrap_content"/>

Layout effect:

strings.xml

  <resources><string name= "App_name" >ALertDialogDemo</string><!--the string resources required for the layout of the main interface-- ><string name= "action_settings" >settings</string><string name= "Simple_dialog" > Basic dialog Box </ String><string name= "Simple_list_dialog" > Simple List dialog box </string><string name= "Single_choice_dialog" > Single Option List dialog box </string><string name= "Multi_choice_dialog" > Multi-Option List dialog </string><string name= " Custom_adapter_dialog "> Customize Adapter Dialog </string><string name=" Custom_view_dialog "> Custom View dialog Box </ string>< string resource required for!--dialog box--><string name= "Dialog_message" > here is the content area </string><string name= " Postive_button "> OK </string><string name=" Negative_button "> Cancel </string><!--dialog box prompt information string resource-- ><string name= "Toast_postive" > You clicked OK button </string><string name= "Toast_negative" > You clicked the Cancel button </ string><string name= "text" > Custom adapter content </string></resources>  

Mainactivity.java

public class Mainactivity extends actionbaractivity implements view.onclicklistener{//corresponds to each buttonprivate Button Simplediaog;private button simplelistdiaog;private button singlechoicediaog;private button multichoicediaog;private Button Customadateprdiaog;private Button customviewdiaog;//declares a alertdialog constructor private Alertdialog.builder builder;@    overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main);    Instantiate the control simplediaog= (Button) Findviewbyid (R.id.btn_simple_dialog);    Simplelistdiaog= (Button) Findviewbyid (R.id.btn_simple_list_dialog);    Singlechoicediaog= (Button) Findviewbyid (R.id.btn_single_choice_dialog);    Multichoicediaog= (Button) Findviewbyid (R.id.btn_multi_choice_dialog);    Customadateprdiaog= (Button) Findviewbyid (R.id.btn_custom_adapter_dialog);    Customviewdiaog= (Button) Findviewbyid (R.id.btn_custom_view_dialog);    Monitor Click event Simplediaog.setonclicklistener (this); SimplelistdiaoG.setonclicklistener (this);    Singlechoicediaog.setonclicklistener (this);    Multichoicediaog.setonclicklistener (this);    Customadateprdiaog.setonclicklistener (this); Customviewdiaog.setonclicklistener (this);} /** * * Each button clicked to pop up the corresponding dialog box, for convenience, write a Showxxdialog () method */@Overridepublic void OnClick (view) {switch (View.getid ())            {Case R.id.btn_simple_dialog:showsimpledialog (view);        Break            Case R.id.btn_simple_list_dialog:showsimplelistdialog (view);        Break            Case R.id.btn_single_choice_dialog:showsinglechoicedialog (view);        Break            Case R.id.btn_multi_choice_dialog:showmultichoicedialog (view);        Break            Case R.id.btn_custom_adapter_dialog:showcustomadapterdialog (view);        Break            Case R.id.btn_custom_view_dialog:showcustomviewdialog (view);    Break }} @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {getmenUinflater (). Inflate (R.menu.menu_main, menu); return true;}}

The above code is relatively simple, and now we really care about is how to specifically implement Showxxdialog;

1. showSimpleDialog() : According to the basic syntax we wrote earlier, we can quickly write the following code, the only thing to note is to listen to two button, because this is the most basic and core Alertdialog, So as long as the master of the other alertdialog is relatively simple;

//显示基本Dialogprivate void showSimpleDialog(View view) {    builder=new AlertDialog.Builder(this);    builder.setIcon(R.mipmap.ic_launcher);    builder.setTitle(R.string.simple_dialog);    builder.setMessage(R.string.dialog_message);    //监听下方button点击事件    builder.setPositiveButton(R.string.postive_button, new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialogInterface, int i) {            Toast.makeText(getApplicationContext(),R.string.toast_postive,Toast.LENGTH_SHORT).show();        }    });    builder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialogInterface, int i) {            Toast.makeText(getApplicationContext(), R.string.toast_negative, Toast.LENGTH_SHORT).show();        }    });    //设置对话框是可取消的    builder.setCancelable(true);    AlertDialog dialog=builder.create();    dialog.show();}
Implementation results:

2, showSimpleListDialog() : The previous code is very similar, the only thing that needs to be changed is to change the content area to a list item:

    private void showSimpleListDialog(View view) {    builder=new AlertDialog.Builder(this);    builder.setIcon(R.mipmap.ic_launcher);    builder.setTitle(R.string.simple_list_dialog);    /**     * 设置内容区域为简单列表项     */    final String[] Items={"Items_one","Items_two","Items_three"};    builder.setItems(Items, new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialogInterface, int i) {            Toast.makeText(getApplicationContext(), "You clicked "+Items[i], Toast.LENGTH_SHORT).show();        }    });    builder.setCancelable(true);    AlertDialog dialog=builder.create();    dialog.show();}
Implementation results:

3, showSingleChoiceDialog() : Note the meaning of the internal parameters of the Setsinglechoiceitems ()

    private void showSingleChoiceDialog(View view) {    builder=new AlertDialog.Builder(this);    builder.setIcon(R.mipmap.ic_launcher);    builder.setTitle(R.string.single_choice_dialog);    /**     * 设置内容区域为单选列表项     */    final String[] items={"Items_one","Items_two","Items_three"};    builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialogInterface, int i) {            Toast.makeText(getApplicationContext(), "You clicked "+items[i], Toast.LENGTH_SHORT).show();        }    });    builder.setCancelable(true);    AlertDialog dialog=builder.create();    dialog.show();}
Implementation results:

4, showMultiCHoiceDialog() :

    private void showMultiChoiceDialog(View view) {    builder=new AlertDialog.Builder(this);    builder.setIcon(R.mipmap.ic_launcher);    builder.setTitle(R.string.simple_list_dialog);    /**     * 设置内容区域为多选列表项     */    final String[] items={"Items_one","Items_two","Items_three"};    builder.setMultiChoiceItems(items, new boolean[]{true, false, true}, new DialogInterface.OnMultiChoiceClickListener() {        @Override        public void onClick(DialogInterface dialogInterface, int i, boolean b) {            Toast.makeText(getApplicationContext(),"You clicked "+items[i]+" "+b,Toast.LENGTH_SHORT).show();        }    });    builder.setCancelable(true);    AlertDialog dialog=builder.create();    dialog.show();}
Implementation results:

5, showCustomAdapterDialog() :

This part involves customizing the adapter, if this part is not very understanding, do not lose heart, in the later article I will explain separately adapter this part. Here we just need to understand that custom adapter need to inherit from Baseadapter, and then we need to overwrite four of them, where the GetView () method is responsible for the display, so we also need to create a layout file for it:
layout->custom_adapter.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:background="#dddddd"android:layout_marginLeft="15dp"android:layout_marginTop="15dp"android:layout_marginBottom="10dp"android:layout_marginRight="15dp"android:layout_width="match_parent"android:layout_height="wrap_content"><ImageView    android:id="@+id/id_image"    android:layout_width="60dp"    android:layout_height="60dp" /><TextView    android:textColor="#554995"    android:id="@+id/id_text"    android:layout_marginLeft="20dp"    android:layout_gravity="center"    android:layout_width="wrap_content"    android:layout_height="wrap_content" />

Layout effect:

We then MainActivity.java implement our custom Adapter classes in the need to :

 Private class Customadapter extends Baseadapter {private list<itembean> items; Private Layoutinflater Inflater; Private ImageView image; private TextView text; Public Customadapter (list<itembean> items, context context) {this.items = items; This.inflater = Layoutinflater.from (context); } @Override public int getcount () {return items.size (); } @Override public Object getItem (int i) {return items.get (i); } @Override public long getitemid (int i) {return i; } @Override public View getView (int i, view view, ViewGroup ViewGroup) {if (view==null) {VIEW=INFL Ater.inflate (R.layout.custom_adapter,null); Image= (ImageView) View.findviewbyid (r.id.id_image); text= (TextView) View.findviewbyid (R.id.id_text); } image.setimageresource (Items.get (i). Getimageid ()); Text.settext (Items.get (i). GetMessage ()); return view; }}

We have used the List items here; It is because adapter needs a picture and a string to fill in the layout we just defined, so we also need to create a data class in mainactivity: Itembean:

Private class itembean{private int imageId;    Private String message;        Public Itembean (int imageId, String message) {This.imageid = ImageId;    this.message = message;    Public String GetMessage () {return message;    } public int Getimageid () {return imageId;    } public void Setimageid (int imageId) {This.imageid = ImageId;    The public void Setmessage (String message) {this.message = message;    }} private void Showcustomadapterdialog (view view) {Builder=new Alertdialog.builder (this);    Builder.seticon (R.mipmap.ic_launcher);    Builder.settitle (R.string.custom_adapter_dialog);    /** * Set content area to custom adapter */list<itembean> items=new arraylist<> ();    Items.Add (New Itembean (R.mipmap.icon, "Can Call Me Xiaoming"));    Items.Add (New Itembean (R.mipmap.ic_launcher, "I ' m Android Xiao"));    Customadapter adapter=new Customadapter (Items,getapplicationcontext ()); Builder.setadapter (Adapter, new DIaloginterface.onclicklistener () {@Override public void OnClick (dialoginterface dialoginterface, int i) {        Toast.maketext (Getapplicationcontext (), "you clicked" +i,toast.length_short). Show ();    }    });    Builder.setcancelable (TRUE);    Alertdialog dialog=builder.create (); Dialog.show ();}
Implementation results:

6, showCustomViewDialog()
To implement the content area of a custom view, we first need to create a layout file:
layout->custom_view.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical "    android:gravity= "center" android:background= "#25AE90" ><linearlayout android:orientation= "Horizontal" Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:layout_marginright= "60DP" Androi d:layout_marginleft= "60DP" > <textview android:text= "user name" android:layout_marginright= "10DP" a Ndroid:textsize= "20SP" android:textcolor= "#ffffff" android:layout_width= "Wrap_content" android:layout _height= "Wrap_content"/> <edittext android:layout_width= "0DP" android:layout_weight= "1" and roid:layout_height= "40DP" android:background= "#ffffff"/></linearlayout><linearlayout Android:orienta  tion= "Horizontal" android:layout_width= "Match_parent"  android:layout_height= "Wrap_content" android:layout_margintop= "10DP" android:layout_marginright= "60DP" Android:        layout_marginleft= "60DP" > <textview android:text= "password" android:layout_marginright= "10DP" Android:textsize= "20SP" android:textcolor= "#ffffff" android:layout_width= "Wrap_content" android:layou t_height= "Wrap_content"/> <edittext android:layout_width= "0DP" android:layout_weight= "1" an droid:layout_height= "40DP" android:background= "#ffffff"/></linearlayout><linearlayout android:orient ation= "Horizontal" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" Android:layout_margin top= "10DP" android:layout_marginright= "60DP" android:layout_marginleft= "60DP" > <button android:text= "Login" android:textcolor= "#25AE90" android:background= "#ECEEF1" android:layout_width= "0DP" and roid:layout_marginright="10DP" android:layout_weight= "1" android:layout_height= "wrap_content"/> <button Android:tex T= "Cancel" android:textcolor= "#25AE90" android:background= "#ECEEF1" android:layout_width= "0DP" a ndroid:layout_weight= "1" android:layout_height= "Wrap_content"/></linearlayout>

Layout effect:

RealizeshowCustomViewDialog()

    private void showCustomViewDialog(View view){    builder=new AlertDialog.Builder(this);    builder.setIcon(R.mipmap.ic_launcher);    builder.setTitle(R.string.custom_view_dialog);    /**     * 设置内容区域为自定义View     */    LinearLayout loginDialog= (LinearLayout) getLayoutInflater().inflate(R.layout.custom_view,null);    builder.setView(loginDialog);    builder.setCancelable(true);    AlertDialog dialog=builder.create();    dialog.show();}
Implementation results:

Summarize:

    • alertdialog Basic usage : Need to master the creation process of Alertdialog, understand the builder model;
    • content Area : The difficulty of Alertdialog is to design the appropriate content area;
    • Custom layouts : Many times we need to customize the display of the Alertdialog content area according to our own wishes, which requires us to master the use of custom adapter and custom view, and these two parts are also a difficult point, to say is another topic;

As the end of the article, in order to test whether we have mastered the various usages of alertdialog, we can try to achieve the following alertdialog; If you have mastered custom adapter and custom ListView, you can try to remove and pin ListItem functionality.

    Tips:编写自定义ListView,监听长按ListItem时弹出AlertDialog,并且实现点击删除能保证ListView中的Item删除掉,并且能够实现置顶功能

    • Weibo: @JueYingCoder,
    • Personal homepage: Coder: Programmers && Engineering men's Daily,

Use of Android Common instance-alert 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.