Android之Dialog的基本使用
activity_mian.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 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context="com.example.demo_dialog.MainActivity" > 10 11 <Button 12 android:id="@+id/main_bt" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:text="点我啊"/> 16 17 </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 bt; 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 bt = (Button)findViewById(R.id.main_bt); 18 bt.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_bt: 27 showDialog(); 28 break; 29 } 30 } 31 }; 32 33 private void showDialog(){ 34 //创建对话框的构造器 35 AlertDialog.Builder builder = new AlertDialog.Builder(this); 36 // 设置图标 37 builder.setIcon(R.drawable.ic_launcher); 38 // 设置标题 39 builder.setTitle("警告"); 40 // 设置消息 41 builder.setMessage("这是一个消息"); 42 // 中间 43 builder.setNeutralButton("ok", click); 44 // 左边 45 builder.setNegativeButton("pass", click); 46 // 右边 47 builder.setPositiveButton("content", click); 48 49 50 // 创建dialog同时显示dialog 51 // builder.show(); 52 53 // 可以调用builder.create(),只创建不显示 54 AlertDialog dialog = builder.create(); 55 // 显示dialog 56 builder.show(); 57 } 58 59 private DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() { 60 61 // dialog参数一个Dialog触发的点击事件 62 // which参数是Dialog中的第几项触发的点击事件 63 @Override 64 public void onClick(DialogInterface dialog, int which) { 65 switch (which) { 66 case DialogInterface.BUTTON_NEGATIVE://-1 67 // pass 68 break; 69 case DialogInterface.BUTTON_POSITIVE://-2 70 // content 71 break; 72 case DialogInterface.BUTTON_NEUTRAL://-3 73 // ok 74 break; 75 } 76 } 77 };