android中点击系统返回键退出


----------------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);
}




相关文章:

  • 2021-06-12
  • 2022-12-23
  • 2021-12-22
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
  • 2021-12-29
  • 2021-11-03
猜你喜欢
  • 2021-05-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-06
  • 2021-12-20
  • 2022-12-23
相关资源
相似解决方案