Android之Dialog列表项对话框
activit_main.xml
1 <RelativeLayout 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 7 8 <Button 9 android:id="@+id/main_item_dialog" 10 android:layout_width="wrap_content" 11 android:layout_height="wrap_content" 12 android:text="点我啊"/> 13 14 </RelativeLayout>
MainActivity.java
1 import android.app.Activity; 2 import android.app.AlertDialog; 3 import android.content.DialogInterface; 4 import android.os.Bundle; 5 import android.view.View; 6 import android.widget.Button; 7 8 9 public class MainActivity extends Activity { 10 11 private Button btDialog; 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 btDialog = (Button)findViewById(R.id.main_item_dialog); 18 btDialog.setOnClickListener(clickListener); 19 } 20 21 private View.OnClickListener clickListener = new View.OnClickListener() { 22 23 @Override 24 public void onClick(View v) { 25 switch (v.getId()) { 26 case R.id.main_item_dialog: 27 showItemDialog(); 28 break; 29 } 30 } 31 }; 32 33 34 private void showItemDialog(){ 35 new AlertDialog.Builder(this) 36 .setItems(new String[]{"水果","蔬菜","积水"}, click) 37 .show(); 38 39 } 40 41 private DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() { 42 43 // dialog参数一个Dialog触发的点击事件 44 // which参数是Dialog中的第几项触发的点击事件 45 @Override 46 public void onClick(DialogInterface dialog, int which) { 47 switch (which) { 48 case DialogInterface.BUTTON_NEGATIVE://-1 49 // pass 50 break; 51 case DialogInterface.BUTTON_POSITIVE://-2 52 // content 53 break; 54 case DialogInterface.BUTTON_NEUTRAL://-3 55 // ok 56 break; 57 } 58 } 59 }; 60 }