Android開發點選返回鍵退出(出現dialog)
阿新 • • 發佈:2019-01-06
重寫activity的如下方法,使其在點選返回按鈕使彈出是否退出:
(注:此方法只針對於只有一個activity的APP,如果存在多個activity可以使用startactivityforresult的處理事件進行,每開啟一個activity均使用startactivityforresult,在利用requestcode值執行關閉。如:1-2,code=1;2-3,code=2;點選返回讓3finish,2的onActivityResult中當請求碼為2時finish,依次類推,就可以實現關閉)
@Override
public boolean dispatchKeyEvent(KeyEvent event) {if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0) {
//具體的操作程式碼
new AlertDialog.Builder(this)
.setTitle("確定退出程式麼")
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();//
}
}).show();
return true;
}
return super.dispatchKeyEvent(event);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case 1:
finish();
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}