----------------activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.g160628_12_widget2.AActivity"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="这是a" android:textSize="50dp"/> </LinearLayout>
---------MainActivity.java
//方法 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //点击返回键 if(keyCode==KeyEvent.KEYCODE_BACK){ //声明弹出对象并初始化 AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle("提示:"); builder.setMessage("是否退出?"); //设置确定按钮 builder.setNegativeButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); //设置取消按钮 builder.setPositiveButton("取消",null); //显示弹窗 builder.show(); } return super.onKeyDown(keyCode, event); }