点击手机上的退出按钮,实现退出警告框的实现
</LinearLayout>
.java文件
package com.example.dialogdemo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class MainActivity extends Activity {
private ImageButton imgButton=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imgButton=(ImageButton) super.findViewById(R.id.imgbut);
//为我们的图片添加事件
this.imgButton.setOnClickListener(new OnClickListenerImp());
}
public class OnClickListenerImp implements OnClickListener{
public void onClick(View arg0) {
MainActivity.this.exitDialog();
}
}
//退出的方法
public void exitDialog(){
Dialog dialog=new AlertDialog.Builder(MainActivity.this)
.setTitle("程序退出?")
.setMessage("您要退出吗")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//确定的话就表示退出,此时我们结束我们程序
//使用我们Activity提供的finish方法
MainActivity.this.finish();//操作结束
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
dialog.show();
}
//此方法用来实现,用户按下返回按钮出现警告提示
public boolean onKeyDown(int keyCode, KeyEvent event) {
//如果用户按下手机上的返回键,出现提示
if(keyCode==KeyEvent.KEYCODE_BACK){
this.exitDialog();
}
return false;
}
}