AlertDialog与Toast皆可用於显示讯息,
但与Toast不同的是,
AlertDialog可与使用者间进行互动,
常用於确认使用者是否执行此步骤。
以下是AlertDialog对话方块常用的方法
而AlertDialog的语法如下
AlertDialog.Builder 变数名称 = new AlertDialog.Builder(主程序类别);
变数名称.setTitle(标题);
变数名称.stIcon(图示);
变数名称.setMessage(内容);
变数名称.按钮名称(按钮文字, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
执行内容
}
});
变数名称.show();
以下为简单的范例,在画面中央设置离开Button,id为exit
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<Button
android:id="@+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结束"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.alertdialog;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button exit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exit = findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("确认视窗");
builder.setMessage("确定要离开APP?");
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
});
}
}
为Button加入监听事件,触发内容为显示AlertDialog,
并为AlertDialog设定Title、Message及两个Button分别是确定及取消,
在确定的执行内容里打上finish()表示按下会结束APP,
最後打上show即完成此范例。
如标题所示 scanner 是取得使用者输入的数,我们的程序不可能一直都是写死的,许多时候我们会需要...
那个…突然想到,Day16写的,ISO 27701 - 个人资料隐私资讯管理系统(隐私资讯管理体系(...
Mac OS 开发系统 完成基本环境设置後 开始新专案 在终端机 Terminal cd 到指定要放...
前言:正确的坐姿很重要 坐姿正确,才能避免腰部受伤,想投身久坐的职业,请爱护身体。 内建型态与变数(...
这篇开始使用 Tag Helper 来 Render 出需要的 Html 控制项 name,方便在 ...