package com.example.yanlei.yl; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.text.Html; import android.text.Html.ImageGetter; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.view.KeyEvent; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //在此方法中创建dialog protected void creatdialog() { //初始化AlertDialog构建器对象 AlertDialog.Builder b = new Builder(MainActivity.this); //设置dialog的信息 b.setMessage("确认退出吗?"); //设置dialog的标题 b.setTitle("提示"); //添加确认和取消按钮 b.setPositiveButton("确认", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //如果用户点击确认退出,则对话框消失,程序关闭 dialog.dismiss(); MainActivity.this.finish(); } }); b.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //如果用户点击取消退出,则对话框消失 dialog.dismiss(); } }); //创建对话框并且显示 b.create().show(); } //在Activity中的键盘监听回调事件 public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { creatdialog(); } return false; } }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <!-- 定义TextView控件 --> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="点击物理返回键弹出退出对话框" /> </RelativeLayout>