Android 监听返回键,弹出确认退出对话框

来源:互联网 发布:怎么看淘宝店铺id 编辑:程序博客网 时间:2024/05/01 18:41
private OnClickListener logoutListener = new OnClickListener(){@Overridepublic void onClick(View v){// TODO Auto-generated method stub//确认注销的对话框AlertDialog.Builder logoutDialog = new AlertDialog.Builder(UserIndexActivity.this);logoutDialog.setTitle("确定注销账号吗?");logoutDialog.setIcon(R.drawable.logout_normal);logoutDialog.setPositiveButton("确认", new DialogInterface.OnClickListener()    {        @Override      public void onClick(DialogInterface dialog, int which)     {    // 点击“确认”后的操作            }      });  logoutDialog.setNegativeButton("返回", new DialogInterface.OnClickListener()     {       @Override      public void onClick(DialogInterface dialog, int which)     {      // 点击“返回”后的操作,这里不设置没有任何操作      }      });        logoutDialog.create().show(); }};


或者


@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event){if (keyCode == KeyEvent.KEYCODE_BACK ){// 创建退出对话框AlertDialog isExit = new AlertDialog.Builder(this).create();// 设置对话框标题isExit.setTitle("系统提示");// 设置对话框消息isExit.setMessage("确定要退出吗");// 添加选择按钮并注册监听isExit.setButton("确定", listener);isExit.setButton2("取消", listener);// 显示对话框isExit.show();}return false;}/**监听对话框里面的button点击事件*/DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener(){public void onClick(DialogInterface dialog, int which){switch (which){case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序finish();break;case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框break;default:break;}}};