(七)android 通知对话框,并且监听了返回键,当按下返回键也会创建一个对话框
一、activity_main.java中代码
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 android:gravity="center" 6 tools:context="com.example.Dialog.MainActivity" > 7 <Button 8 android:onClick="click" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 android:text="对话框" /> 12 </LinearLayout>
二、MainActivity.java中的代码
1 package com.example.Dialog; 2 3 import android.app.Activity; 4 import android.app.AlertDialog; 5 import android.app.AlertDialog.Builder; 6 import android.app.Dialog; 7 import android.content.DialogInterface; 8 import android.content.DialogInterface.OnClickListener; 9 import android.os.Bundle; 10 import android.view.KeyEvent; 11 import android.view.View; 12 import android.widget.Toast; 13 14 public class MainActivity extends Activity { 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 } 21 22 public void click(View view) { 23 AlertDialog.Builder builder = new Builder(this); 24 builder.setTitle("提示"); 25 builder.setIcon(R.drawable.ic_launcher); 26 builder.setMessage("是否要进行软件升级"); 27 // builder.setCancelable(false); 28 builder.setPositiveButton("确定", new OnClickListener() { 29 @Override 30 public void onClick(DialogInterface dialog, int which) { 31 // TODO Auto-generated method stub 32 Toast.makeText(MainActivity.this, "确定被点击了", 0).show(); 33 } 34 }); 35 builder.setNegativeButton("取消", new OnClickListener() { 36 37 @Override 38 public void onClick(DialogInterface dialog, int which) { 39 // TODO Auto-generated method stub 40 Toast.makeText(MainActivity.this, "取消被点击了", 0).show(); 41 } 42 }); 43 builder.create().show(); 44 } 45 46 @Override 47 public boolean onKeyDown(int keyCode, KeyEvent event) { 48 // TODO Auto-generated method stub 49 50 if (keyCode == KeyEvent.KEYCODE_BACK) { 51 AlertDialog.Builder builder = new Builder(this); 52 builder.setTitle("提示"); 53 builder.setMessage("确定要退出吗"); 54 builder.create(); 55 Dialog dialog; 56 57 builder.setPositiveButton("确定", new OnClickListener() { 58 59 @Override 60 public void onClick(DialogInterface dialog, int which) { 61 // TODO Auto-generated method stub 62 dialog.dismiss(); 63 } 64 }); 65 builder.setNegativeButton("取消", new OnClickListener() { 66 67 @Override 68 public void onClick(DialogInterface dialog, int which) { 69 // TODO Auto-generated method stub 70 71 } 72 }); 73 dialog = builder.show(); 74 75 } 76 return false; 77 } 78 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。