首先创建页面布局:
然后设置activity:
package com.example.administrator.myapplication;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
//控制手机自带按钮的一些属性的方法
public class DialogActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//点击返回键
if(keyCode==KeyEvent.KEYCODE_BACK){
//声明弹出对象并初始化
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("提示:");
builder.setMessage("是否退出?");
//设置确定按钮
builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
//设置取消按钮
builder.setPositiveButton("取消",null);
//显示弹窗
builder.show();
}
return super.onKeyDown(keyCode,event);
}
}