當進入應用程式,按下手機上的"返回鍵"時,需出現訊息視窗,請使用者確認是否離開此應用程式。
這一篇比 "[android範例] 按下返回鍵出現確認離開視窗2" 更加強了防止重複按下退出鍵判斷、dialog.dismiss()。
程式結果畫面如下:
程式:
package com.example.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onKeyDown(int keyCode,KeyEvent event){
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){ //確定按下退出鍵and防止重複按下退出鍵
dialog();
}
return false;
}
private void dialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); //創建訊息方塊
builder.setMessage("確定要離開?");
builder.setTitle("離開");
builder.setPositiveButton("確認", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //dismiss為關閉dialog,Activity還會保留dialog的狀態
MainActivity.this.finish();//關閉activity
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
留言列表