Android 項目常見的退出方式有兩種一種是彈出dialog對話框提示用戶退出應用,下面就兩種實現形式有示列代碼能夠參考:ide
第一種彈出dialog樣式退出方式:ui
1.第一步首先要監測用戶是否按下back鍵,就要重寫onKeyDown()blog
2.構建dialog圖片
主要代碼以下:it
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event != null && keyCode == event.KEYCODE_BACK) {
alertDialog();
}
return false;
}
private void alertDialog(){
CharSequence charTitle = "退出";
CharSequence charMessage = "您肯定退出嗎?";
CharSequence [] charSequence = new CharSequence[]{"肯定","取消"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mActivity)
.setIcon(R.drawable.ic_launcher)//設置頭部圖片
.setTitle(charTitle)//設置標題
.setMessage(charMessage)//設置提示內容
.setPositiveButton(charSequence[0], new DialogInterface.OnClickListener() {//肯定按鈕監聽
@Override
public void onClick(DialogInterface dialog, int which) {
/**
* 可添加項目處理邏輯
*/
mActivity.finish();
}
})
.setNegativeButton(charSequence[1], new DialogInterface.OnClickListener() {//取消按鈕監聽
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}io
效果以下:event
第二種雙擊兩次back鍵退出樣式ast
主要代碼以下:sed
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event != null && keyCode == event.KEYCODE_BACK) {
exitApp();
}
return false;
}List
/**
* 雙擊退出應用
*/
private boolean isExit = false;
private void exitApp(){
if (isExit == false) {
isExit = true;
Toast.makeText(mActivity, "再按一下退出", Toast.LENGTH_LONG).show();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
isExit = false;
}
}, 2000);
}else{
mActivity.finish();
}
}
效果圖以下:
另外一種實現方式:
@Override
public void onBackPressed() {
if(backToFinish())finish();
}
/**
* 雙擊退出
*/
private int BACK = 0;
private boolean backToFinish(){
if(BACK==0){
BACK++;
Toast.makeText(mActivity,"再按一次退出", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1500);
BACK--;
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
return false;
}else if(BACK==1){
return true;
}
return true;
}
內容很簡單,但願對你有所幫助!