实际效果:
实例代码:
后台逻辑:
package com.example.tf.dialog_demo;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements DialogInterface.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void simple(View view){
//实例化对话框的内部类Builder(构建器)对象
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("登录提示");
builder.setMessage("正在登录......");
builder.setIcon(R.mipmap.ic_launcher);
builder.setCancelable(false);
builder.setPositiveButton("保存", this);
builder.setNegativeButton("不保存",this);
builder.setNeutralButton("取消",this);
}
@Override
public void onClick(DialogInterface dialogInterface, int which) {
if(DialogInterface.BUTTON_POSITIVE==which){
Toast.makeText(getApplicationContext(),"用户点击了保存按钮",Toast.LENGTH_LONG).show();
}else if(DialogInterface.BUTTON_NEGATIVE==which){
Toast.makeText(getApplicationContext(),"用户点击了不保存按钮",Toast.LENGTH_LONG).show();
}else if (DialogInterface.BUTTON_NEUTRAL==which){
Toast.makeText(getApplicationContext(),"用户点击额取消按钮",Toast.LENGTH_LONG).show();
}
}
@Override
public void onBackPressed() {
//super.onBackPressed();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("退出提示");
builder.setMessage("你确定要退出应用程序吗?");
builder.setPositiveButton("是",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int which) {
Toast.makeText(getApplicationContext(), "保存退出", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
Toast.makeText(getApplicationContext(), "不保存退出", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("取消",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(), "返回应用程序", Toast.LENGTH_SHORT).show();
}
});
builder.create().show();
System.out.println("====onBackPressed====");
}
}