Android Common dialog box encapsulation

Source: Internet
Author: User

In the development of Android, the dialog is often used to interact with the user, user-friendly, easy to operate, then the common dialog box is simple encapsulation, to avoid redundant code in the project, to increase the maintenance of the post-project; code if there is a problem welcome everyone to make a progress together.

First put out the demo results, in the sun out the demo code.
1. After successful operation, the original interface is as follows:

2. Click "Show Normal Dialog", the effect interface is as follows:

3. Click "Show List Dialog", the effect interface is as follows:

4. Click "Show Radio Button Dialog", the effect interface is as follows:

5. Click "Show Check Dialog", the effect interface is as follows:

Code:
1. The project directory structure is as follows

2, dialog box packaging class Dialogtool

Package Com.hrtx.util; import Android.app.dialog;import Android.content.context;import android.content.dialoginterface.onclicklistener; /** * dialog box wrapper class  *  * @author jiqinlin *  */public class Dialogtool {      /**     * Create a normal dialog box      *      * @param ctx must be filled in the context of      * @ param iconID icon, such as: R.drawable.icon must fill      * @param title title must be filled      * @param message display must be filled in      * @param btnname button name is required      * @param Listener listener, need to implement Android.content.DialogInterface.OnClickListener interface must fill      * @return       */ public static Dialog Createnormaldialog (Context ctx,    int iconId,    string title,    string message,    string btnname,    onclicklistener listener) {  dialog Dialog=null;  android.app.alertdialog.builder Builder = new Android.app.AlertDialog.Builder (CTX);   //Settings Dialog Icon   builder.seticon (iconID);   //the caption of the settings dialog   builder.settitle (title);   //Settings dialog box display    Builder.setmessage (message);   //Add button, Android.content.DialogInterface.OnClickListener.OnClickListener   builder.setpositivebutton (btnname, listener);   //Create a normal dialog box   dialog = Builder.create ();   return dialog; }        /**      * Create List dialog box      *      * @param ctx must fill in the context      * @param iconid icon, such as: R.drawable.icon required      * @param title Required      * @param itemsid string array resource ID required      * @param listener listener, Need to implement Android.content.DiaLoginterface.onclicklistener interface Required      * @return      */  public static Dialog Createlistdialog (Context ctx,    int iconID,    string title,     int Itemsid,    onclicklistener listener) {  dialog dialog=null;   Android.app.AlertDialog.Builder Builder = new Android.app.AlertDialog.Builder (CTX);   //Settings dialog box icon    builder.seticon (iconID);   //set the title of the dialog   builder.settitle (title);   //Add button, Android.content.dialoginterface.onclicklistener.onclicklistener  builder.setitems (itemsId, listener);   //Create a list dialog box   dialog = Builder.create ();   return dialog; }       /**     * Create a radio button dialog box      *       * @param ctx must fill      * @param iconid icon, such as: R.drawable.icon required andnbsp;    * @param title title required      * @param itemsid string array resource ID must be filled       * @param Listener radio button item listener, need to implement Android.content.DialogInterface.OnClickListener interface must fill       * @param btnname button name is required      * @param listener2 button Listener, Required to implement Android.content.DialogInterface.OnClickListener interface must be filled      * @return       */ public static Dialog Createradiodialog (Context ctx,    int iconID,     string title,    int itemsid,    onclicklistener listener,    String Btnname,   onclicklistener listener2) {  dialog dialog=null;   Android.app.AlertDialog.Builder Builder = new Android.app.AlertDialog.Builder (CTX);   //Settings dialog box icon    builder.seticon (iconID);   //set the title of the dialog box   builder.settitle (title);   //0: The default first radio button isSelect   builder.setsinglechoiceitems (itemsid, 0, listener);   //Add a button    Builder.setpositivebutton (Btnname, listener2);   //Create a radio button dialog box   dialog = Builder.create ();   return dialog; }        /**      * Create Check dialog box      *      * @param ctx Required       * @param iconid icon, such as: R.drawable.icon required      * @param title must be filled       * @param itemsid string array resource ID required      * @param flags initial check required       * @param Listener radio button item listener, need to implement Android.content.DialogInterface.OnMultiChoiceClickListener interface must fill      * @param btnname button name is required      * @param listener2 button Listener, Required to implement Android.content.DialogInterface.OnClickListener interface must be filled      * @return        */ public static Dialog Createcheckboxdialog (Context ctx,    int iconID,     String title,    int itemsid,    boolean[] flags,    Android.content.DialogInterface.OnMultiChoiceClickListener listener,   string btnname,    onclicklistener listener2) {  dialog dialog=null;   Android.app.AlertDialog.Builder Builder = new Android.app.AlertDialog.Builder (CTX);   //Settings dialog box icon    builder.seticon (iconID);   //the title of the Settings dialog   builder.settitle (title);   Builder.setmultichoiceitems (ITEMSID, flags, listener);   //Add a button   builder.setpositivebutton ( Btnname, Listener2)   //Create a check dialog box   dialog = Builder.create ();   return dialog; } }

3, dialog box activity class Dialogactivity

Package Com.ljq.activity; import Android.app.activity;import Android.app.dialog;import Android.content.dialoginterface;import Android.os.bundle;import Android.view.view;import Android.widget.Button; Import android.widget.edittext;import android.widget.toast; /** * dialog box activity class  *  * @author Jiqinlin * */public class Dialogactivity extends Activity { private boolean[] flags=new boolean[]{false , true,false}; Initial check case  private string[] items=null;      private EditText ettext=null;     private button Btnnormal=null;    private button btnlist=null;     private button Btnradio=null;    private button btnCheckBox=null;          private static final int dialog_normal=0; Normal dialog constant     private static final int dialog_list=1; List dialog Constants     private static final int DIAlog_radio=2; radio Button dialog box constant     private static final int dialog_checkbox=3; Check dialog box Constants           @Override     public void OnCreate (Bundle savedinstancestate) {        super.oncreate ( Savedinstancestate);         setcontentview (R.layout.main);                  items=getresources () . Getstringarray (R.array.hobby);                  ettext= (EditText) Findviewbyid (r.id.ettext);         btnnormal= (Button) Findviewbyid (r.id.btnnormal);         btnlist= ( button) Findviewbyid (r.id.btnlist);         btnradio= (Button) Findviewbyid (R.id.btnradio);         btncheckbox= (Button) Findviewbyid (R.id.btncheckbox);         btnnormal.setonclicklistener (L);         Btnlist.setonclicklistener (l);         btnradio.setonclicklistener (L);         btncheckbox.setonclicklistener (l);     }           @Override     protected Dialog Oncreatedialog (int id) {     dialog dialog=null;     switch (ID) {  case Dialog_normal://Create Normal Dialog    dialog = Dialogtool.createnormaldialog (This,       r.drawable.icon,       "Normal dialog",       " This is the content of the normal dialog box! ",      " OK ",         new Android.content.DialogInterface.OnCLicklistener () {       @Override       public void OnClick (dialoginterface dialog, int which) {       ettext.settext ("This is the content of the normal dialog box! ");       return;      }               }             )    break;  case dialog_list://Create List dialog box     dialog = Dialogtool.createlistdialog (this,      r.drawable.icon,        List dialog box,      r.array.hobby,          new Android.content.DialogInterface.OnClickListener () {       @Override        public void OnClick (dialoginterface dialog, int which) {         string hoddy=getresources (). Getstringarray (r.array.hobby) [which];             ettext.settext ("You have selected:" +hoddy);       return;       }               }            );    break ;   case Dialog_radio://Create radio Button dialog box    dialog=dialogtool.createradiodialog (this,       R.drawable.icon,      radio Button dialog box,      R.array.hobby,         new Android.content.DialogInterface.OnClickListener () {       @Override        public void OnClick (dialoginterface dialog, int which) {        string Hoddy = Getresources (). Getstringarray (         r.array.hobby) [which];        ettext.settext ("You have selected:" + Hoddy);       return;       }     },         "OK",            new Android.content.DialogInterface.OnClickListener () {       @Override       public void OnClick ( Dialoginterface dialog, int which) {       toast.maketext (DialogActivity.this,           "You pressed the OK button!" ", Toast.length_long). Show ();       return;       }     }   );    break;  case Dialog_ CheckBox://Create check box dialog box    dialog=dialogtool.creatEcheckboxdialog (This,      R.drawable.icon,      Check dialog box,      r.array.hobby,     flags,       New Dialoginterface.onmultichoiceclicklistener () {      public void OnClick ( Dialoginterface dialog, int which, Boolean isChecked) {       flags[which] = ischecked;       string result = "You have selected:";        for (int i = 0; i < flags.length; i++) {        if (Flags[i]) {&NBSP;&NB Sp;       result = result + Items[i] + ",";         }       }        Ettext.settext (result.substring (0, Result.length ()-1));      }      },      "Confirm",            new Android.content.DialogInterface.OnClickListener () {       @Override        public void OnClick (dialoginterface dialog, int which) {        toast.maketext (dialogactivity.this, "You pressed the OK button! ", Toast.length_long). Show ();       return;       }     }          );    break;  }     return dialog;    }          //button Monitor     view.onclicklistener l = new View.onclicklistener () {   @Override   public void OnClick (View v) {   button btn = ( Button) V;   switch (Btn.getid ()) {  &nbsP;case r.id.btnnormal://Normal Dialog                  //Display dialog box     showdialog (dialog_normal);    break;    case r.id.btnlist://List dialog box                  //Display dialog box     showdialog (dialog_list);     Break;   case R.id.btnradio://radio button dialog box                  //Display dialog box     showdialog (DIALOG_RADIO);     break;   case R.id.btncheckbox://Check dialog box                  //Display dialog box     showdialog (DIALOG_ CHECKBOX);     break;   }  } };}

4. layout file Main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:orientation=" vertical "android:layout_width=" fill_parent "     android:layout_height= "Fill_parent" >    <edittext android:text= ""          android:id= "@+id/ettext"          android:layout_width= "Fill_parent"         android:layout_height= "Wrap_content"         android:editable= "false"          android:cursorvisible= "false"/>    <button android:text= " Show normal dialog "        android:id=" @+id/btnnormal "         android:layout_width= "Fill_parent"          android:layout_height="Wrap_content"/>    <button android:text= "Show list box"          android:id= "@+id/btnlist"         android:layout_width= " Fill_parent "        android:layout_height=" Wrap_content "/>     <button android:text= "Show radio button dialog box"         android:id = "@+id/btnradio"         android:layout_width= "Fill_parent"          android:layout_height= "Wrap_content"/>    < Button android:text= "Show check dialog box"         android:id= "@+id/btncheckbox"         android:layout_width= "Fill_parent"          android:layout_height= "Wrap_content"/></linearlayout>

5. Array variable Array.xml

<?xml version= "1.0" encoding= "Utf-8"?><!--the use of resources Resoureces is the RES directory of those directories and files, commonly used are: res/drawable/  Used to store picture files res/layout/used to store layout definition files res/values/used to store variables, parameters and other files--><resources> <string-array name= "Hobby" > <item> Swimming </item> <item> playing basketball </item> <item> mountaineering </item> </string-array></ Resources>

6. manifest file

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "      package=" Com.ljq.activity "       Android:versioncode= "1"       android:versionname= "1.0" >     <application android:icon= "@drawable/icon" android:label= "@string/app_name" >         <activity android:name= ". Dialogactivity "                   android:label= "@string/app_name" >             <intent-filter>                 <action android:name= "Android.intent.action.MAIN"/>                 <category anDroid:name= "Android.intent.category.LAUNCHER"/>             </intent-filter>        </activity>  &NBSP;&NBSP;&NBSP;&NBSP;&LT;/APPLICATION&GT;&NBSP;&NBSP;&NBSP;&NBSP;&LT;USES-SDK android:minSdkVersion= "4"/>  </manifest>

Android common dialog box encapsulation

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.