In Android development, we often need to pop up some dialog boxes on the Android interface, such as asking the user or letting the user choose. These features we call it Android Dialog dialog box, Alertdialog implementation method for Builder mode. Let's simply simulate the selection of an emperor's chosen concubine to determine the dialog box (multiple selection), such as:
Layout (only one button is assigned) interface code:
1<?xml version= "1.0" encoding= "Utf-8"?>2<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"3Xmlns:tools= "Http://schemas.android.com/tools"4Android:id= "@+id/activity_main"5Android:layout_width= "Match_parent"6android:layout_height= "Match_parent"7tools:context= "Com.example.administrator.multichoice.MainActivity" >8<Button9android:text= "Multiple Selection"TenAndroid:layout_width= "Match_parent" Oneandroid:layout_height= "Wrap_content" AAndroid:id= "@+id/button" -android:onclick= "Show"/> -</RelativeLayout>
Java Implementation code:
1 ImportAndroid.content.DialogInterface;2 ImportAndroid.support.v7.app.AlertDialog;3 Importandroid.support.v7.app.AppCompatActivity;4 ImportAndroid.os.Bundle;5 ImportAndroid.view.View;6 ImportAndroid.widget.Toast;7 Importjava.util.ArrayList;8 Importjava.util.List;9 Ten Public classMainactivityextendsappcompatactivity { One //instantiate a collection that stores the user's final selection AList<string> Choose =NewArraylist<>(); - @Override - protected voidonCreate (Bundle savedinstancestate) { the Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); - } - Public voidShow (View v) { +Alertdialog.builder Builder =NewAlertdialog.builder ( This); -Builder.settitle ("The emperor chose his concubine.")); + FinalString[] names={"Xi Shi", "Wang Zhaojun", "Marten Cicada", "Yang Yuhuan"}; AChoose.clear ();//empty The elements in the collection before each click event at //Set dialog to multi-box with no default option (NULL) -Builder.setmultichoiceitems (Names,NULL,NewDialoginterface.onmultichoiceclicklistener () { - @Override - //Set the Click event: If checked, add the Choose, or move out if it is canceled or not selected choose - Public voidOnClick (Dialoginterface Dialog,intWhich,BooleanisChecked) { - if(isChecked) { in Choose.add (Names[which]); -}Else{ to Choose.remove (Names[which]); + } - } the }); * //Set the front button and click events (toast display choose content) $Builder.setpositivebutton ("OK",NewDialoginterface.onclicklistener () {Panax Notoginseng @Override - Public voidOnClick (Dialoginterface Dialog,intwhich) { theToast.maketext (mainactivity. This, choose.tostring () + "It's Your concubine.", Toast.length_short). Show (); + } A }); theBuilder.show ();//Show Dialog dialog box + } -}
We can communicate more, perfect the dialogue box, I wish you all happy to masturbate
Alertdialog in Android uses example four (multiple selection OK dialog box)