android中点击系统返回键退出

来源:互联网 发布:中国移动免流量软件 编辑:程序博客网 时间:2024/05/18 12:41


----------------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
//方法@Overridepublic 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);}


原创粉丝点击