activity_main.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context="com.example.demo_dialog.MainActivity" 6 android:orientation="horizontal" > 7 8 <Button 9 android:id="@+id/main_item" 10 android:layout_width="wrap_content" 11 android:layout_height="wrap_content" 12 android:text=".点我啊...."/> 13 14 </LinearLayout>
value文件夹下的arrays.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <!-- 资源数组 --> 3 <resources> 4 <string-array name="single_chooice"> 5 <item>男</item> 6 <item>女</item> 7 </string-array> 8 </resources>
MainActivity.java
1 import android.app.Activity; 2 import android.app.AlertDialog; 3 import android.content.DialogInterface; 4 import android.content.DialogInterface.OnMultiChoiceClickListener; 5 import android.os.Bundle; 6 import android.util.Log; 7 import android.view.View; 8 import android.widget.Button; 9 10 11 public class MainActivity extends Activity { 12 13 private Button btItem; 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.activity_main); 18 btItem = (Button)findViewById(R.id.main_item); 19 btItem.setOnClickListener(clickListener); 20 } 21 22 private View.OnClickListener clickListener = new View.OnClickListener() { 23 24 @Override 25 public void onClick(View v) { 26 switch (v.getId()) { 27 case R.id.main_item: 28 showSingDialog(); 29 break; 30 } 31 } 32 }; 33 34 private void showSingDialog(){ 35 new AlertDialog.Builder(this) 36 // 参数1:数据(可以是资源数组也可以是String数组) 参数2:默认选中项 参数3:点击事件 37 .setSingleChoiceItems(R.array.single_chooice, 1, click); 38 } 39 40 private void showItemDialog(){ 41 new AlertDialog.Builder(this) 42 .setItems(new String[]{"水果","蔬菜","积水"}, click) 43 .show(); 44 } 45 46 private DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() { 47 48 // dialog参数一个Dialog触发的点击事件 49 // which参数是Dialog中的第几项触发的点击事件 50 @Override 51 public void onClick(DialogInterface dialog, int which) { 52 switch (which) { 53 case DialogInterface.BUTTON_NEGATIVE://-1 54 Log.i("aaa", "======BUTTON_NEGATIVE====="+which); 55 break; 56 case DialogInterface.BUTTON_POSITIVE://-2 57 Log.i("aaa", "======BUTTON_POSITIVE====="+which); 58 break; 59 case DialogInterface.BUTTON_NEUTRAL://-3 60 Log.i("aaa", "======BUTTON_NEUTRAL====="+which); 61 break; 62 } 63 } 64 }; 65 }