Android 回退操作的两种方式

一 . Dialog弹框


/**添加回退操作监听器*/
@Override
public void onBackPressed() {
AlertDialog.Builder bd = new AlertDialog.Builder(this);
//设置图标
bd.setIcon(android.R.drawable.btn_star);
//设置标题
bd.setTitle("标题");
//设置标题内容
bd.setMessage("确定退出吗?");
//添加选项

/**②加了选项的退出操作*/
/**items = new String[]{"清空浏览记录","其他"};
bd.setMultiChoiceItems(items,//选项
flags,//设置选中项
cListener);//监听器*/
//添加按钮
/**①没加选项的退出操作*/
bd.setNegativeButton("取消", btnListener);
bd.setPositiveButton("确定", btnListener);
//创建对话框
AlertDialog dialog = bd.create();
//显示对话框
dialog.show();
//dialog.cancel();//销毁对话框
}
/**②加了选项的退出操作*/
/**private List checkets = new ArrayList();
private DialogInterface.OnMultiChoiceClickListener cListener = 
new DialogInterface.OnMultiChoiceClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which,//item的位置
boolean isChecked) {
if (isChecked) {
checkets.add(items[which]);
}else {
if(checkets.contains(items[which])){
checkets.remove(items[which]);
}
}
}
};*/
/**①没加选项的退出操作*/
private DialogInterface.OnClickListener btnListener =
new OnClickListener(){


@Override
public void onClick(DialogInterface dialog, int which) {
switch(which){
case DialogInterface.BUTTON_POSITIVE:
finish();
dialog.cancel();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.cancel();
break;
}
}

};



二 . Toast 吐司显示

     

     private Handler handler;

  private boolean isExit;
@Override
public void onBackPressed() {
if (!isExit) {
Toast.makeText(this, "有事没事别老是点退出!", 1).show();
isExit = true;
//发送延迟信息
handler.postDelayed(new Runnable() {
@Override
public void run() {
isExit = false;
}
}, 3000);
}else{
//销毁
finish();
}
}

你可能感兴趣的:(Android)