效果图

步骤
1. 新建一个 project
2. 编辑activity_main.xml问文件 (代码见后面)
android:onClick="onClickShowAlert" //按钮设置为 点击响应
红色提示,选择 alt+enter常见方法,下面重写
3.重写onClickShowAlert
响应方法
Builder 设计模式 ,是为了
The Builder is a design pattern designed to provide a flexible
solution to various object creation problems in object-oriented
programming. The intent of the Builder design pattern is to separate
the construction of a complex object from its representation. It is
one of the Gang of Four design patterns.
public void onClickShowAlert(View view) {
// 使用Builder模式构建
AlertDialog.Builder myAlertBuilder = new
AlertDialog.Builder(MainActivity.this);
myAlertBuilder.setTitle(R.string.alert_title); //设置Title
myAlertBuilder.setMessage(R.string.alert_message); //设置显示信息
//设置正向反馈后的操作
myAlertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Pressed OK",Toast.LENGTH_SHORT).show();
}
});
//设置负向反馈后的操作
myAlertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Pressed Cancel",Toast.LENGTH_SHORT).show();
}
});
myAlertBuilder.show();
}
ps:xml中的代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/HelloWorld"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:onClick="onClickShowAlert"
android:text="@string/alert_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</android.support.constraint.ConstraintLayout>