下面為您介紹此實用程式碼:
public boolean onKeyDown(int keyCode, KeyEvent event) {//捕捉返回鍵
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
ConfirmExit();//按返回鍵,則執行退出確認
return true;
}
return super.onKeyDown(keyCode, event);
}
public void ConfirmExit(){//退出確認
AlertDialog.Builder ad=new AlertDialog.Builder(MyOpenDataActivity.this);
ad.setTitle("離開");
ad.setMessage("確定要離開?");
ad.setPositiveButton("是", new DialogInterface.OnClickListener() {//退出按鈕
public void onClick(DialogInterface dialog, int i) {
// TODO Auto-generated method stub
MyOpenDataActivity.this.finish();//關閉activity
}
});
ad.setNegativeButton("否",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
//不退出不用執行任何操作
}
});
ad.show();//示對話框
}
只要在onCreate之外加入上面這段程式碼,程式就會在該Activity加入按下返回鍵時的詢問。
沒有留言:
張貼留言
您的寶貴建議是我前進的動力!