示例圖:
1 :創建 AlertDialog.Builder 對象;
2 :調用 setIcon() 設置圖標, setTitle() 或 setCustomTitle() 設置標題;
3 :設置對話框的內容: setMessage() 還有其他方法來指定顯示的內容;
4 :調用 setPositive/Negative/NeutralButton() 設置:確定,取消,中立按鈕;
5 :調用 create() 方法創建這個對象,再調用 show() 方法將對話框顯示出來;
MainActivity.java
package com.example.myalertdialog;import androidx.appcompat.app.AppCompatActivity;import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import java.util.ArrayList;
import java.util.List;// AlertDialog對話框 應用
public class MainActivity extends AppCompatActivity implements View.OnClickListener {//組件private Button btnOne,btnTwo,btnThree,btnFour,btnFive;private TextView textView;private Context context;//對話框private AlertDialog.Builder builder =null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);context =this;btnOne = findViewById(R.id.btn_one);btnTwo = findViewById(R.id.btn_Two);btnThree = findViewById(R.id.btn_three);btnFour =findViewById(R.id.btn_four);btnFive = findViewById(R.id.btn_five);textView = findViewById(R.id.btn_tv);//設置事件btnOne.setOnClickListener(this);btnTwo.setOnClickListener(this);btnThree.setOnClickListener(this);btnFour.setOnClickListener(this);btnFive.setOnClickListener(this);}@Overridepublic void onClick(View v) {if(v.getId() == R.id.btn_one){//普通對話框builder = new AlertDialog.Builder(context);//標題builder.setTitle("游戲提示:");//logobuilder.setIcon(R.mipmap.a);//內容builder.setMessage("您確認要開始游戲嗎?");//確定按鈕builder.setPositiveButton("開始", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(context ,"開始游戲",Toast.LENGTH_SHORT).show();}});//取消按鈕 null 表示什么都不做builder.setNegativeButton("取消",null);//中立按鈕builder.setNeutralButton("中立", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(context,"中立您選擇了"+which,Toast.LENGTH_SHORT).show();}});//創建 顯示builder.create().show();}else if (R.id.btn_Two == v.getId()) {//單選對話框 1 只能選一次//數據源final String[] arr = new String[]{"校長","老師","學生","家長"};//單選對話框builder = new AlertDialog.Builder(context);//標題builder.setTitle("請選擇您的身份:");//圖標builder.setIcon(R.mipmap.a);//內容builder.setItems(arr, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(context,"您選擇了"+arr[which],Toast.LENGTH_SHORT).show();textView.setText(arr[which]);}});//取消按鈕builder.setNegativeButton("取消",null);//創建 顯示builder.create().show();} else if (v.getId() == R.id.btn_three) {// 單選對話框2 可反復選擇builder = new AlertDialog.Builder(context);//數據源 2final String[] arr = new String[]{"java","php","android","c++"};//標題builder.setTitle("請選擇課程:");//圖標builder.setIcon(R.mipmap.a);//內容 默認選擇項 -1表示不選擇 0表示選中第一個builder.setSingleChoiceItems(arr, -1, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(context,"您選擇了"+arr[which],Toast.LENGTH_SHORT).show();textView.setText(arr[which]);}});//取消按鈕builder.setNegativeButton("取消",null);//創建 顯示builder.create().show();} else if (v.getId() == R.id.btn_four) {// 多選對話框builder = new AlertDialog.Builder(context);//選擇后的集合List<String> datas = new ArrayList<>();//數據源final String[] arr = {"胡蘿卜炒肉","辣椒炒蛋","水煮活魚","清蒸龍蝦"};//標題builder.setTitle("請選擇菜單:");//圖標builder.setIcon(R.mipmap.a);//內容 setMultiChoiceItems// 數據源,默認選中哪幾個, null 表示一個都不選// new boolean[]{false, false, true, true}builder.setMultiChoiceItems(arr, null, new DialogInterface.OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which, boolean isChecked) {if(isChecked){datas.add(arr[which]);}else{datas.remove(arr[which]);}}});//確定按鈕 setPositiveButtonbuilder.setPositiveButton("確認", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(context,"您選擇了"+datas.toString(),Toast.LENGTH_SHORT).show();textView.setText(datas.toString());}});//取消builder.setNeutralButton("取消",null);//創建 顯示builder.create().show();}if(v.getId() == R.id.btn_five){// 適配器對話框 調用寫的方法builder = AlertSimplAdapter.getAlertBuilder(context);//創建 顯示builder.create().show();}}}
寫一個方法類?AlertSimplAdapter.java
package com.example.myalertdialog;import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.SimpleAdapter;
import android.widget.Toast;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class AlertSimplAdapter {//圖片private static final int[] arrImg = new int[]{R.mipmap.a, R.mipmap.b, R.mipmap.c,R.mipmap.d, R.mipmap.e, R.mipmap.f,R.mipmap.g, R.mipmap.h, R.mipmap.i,R.mipmap.a, R.mipmap.a, R.mipmap.a,R.mipmap.a, R.mipmap.a, R.mipmap.a};//標題private static final String[] arrTitle = {"張三","李四","張三豐","小學群聊","周芷若","周先生","老領導","玖龍璽","阿道夫","張三","李四","張三豐","張三","李四","張三豐"};//內容private static String[] arrContent =new String[]{"早啊!","你在干啥","你最近在練什么武功","呼叫XXX家長","最近咋樣","吃飯了嗎?","啥時候有空喝茶呀?",".....","小伙子,學魔法嗎?","早啊!","你在干啥","你最近在練什么武功","早啊!","你在干啥","你最近在練什么武功"};//時間private static String[] arrTime = {"剛剛","昨天","11-20","10-1","2023-11-20","17:30","9:00","10-1","2000-01-01","剛剛","昨天","11-20","剛剛","昨天","11-20"};public static AlertDialog.Builder getAlertBuilder(Context context){AlertDialog.Builder builder = new AlertDialog.Builder(context);//標題builder.setTitle("**通訊信息**");//logobuilder.setIcon(R.mipmap.a);//設置數據源 List<? extends Map<String, ?>> dataList<Map<String, Object>> datas = new ArrayList<>();for(int i =0 ; i<arrImg.length;i++) {//各項數據Map<String, Object> itemData = new HashMap<>();itemData.put("item_img", arrImg[i]);itemData.put("item_title", arrTitle[i]);itemData.put("item_content", arrContent[i]);itemData.put("item_time", arrTime[i]);//添加到Listdatas.add(itemData);}// 第1個參數: Context
// 第2個參數: 數據 List<map<String,Object>> datas
// 第3個參數: xml資源文件 R.layout....
// 第4個參數: 控制從datas中取出哪些數據 與map中的 key一致
// 第5個參數: 布局文件的id 控制取出的數據要填充哪些界面元素。SimpleAdapter simpleAdapter = new SimpleAdapter(context,datas,R.layout.content_layout,new String[]{"item_img","item_title","item_content","item_time"},new int[]{R.id.btn_image_view,R.id.btn_title_view,R.id.btn_tv_content,R.id.btn_time});//內容 設置適配器builder.setAdapter(simpleAdapter, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(context, "您選擇了"+which, Toast.LENGTH_SHORT).show();}});//取消builder.setPositiveButton("取消",null);return builder;}
}
主布局文件 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"android:layout_height="match_parent"tools:context=".MainActivity"><TextViewandroid:id="@+id/btn_tv"android:text="您選擇了:"android:textSize="24sp"android:layout_width="wrap_content"android:layout_height="wrap_content"/><Buttonandroid:id="@+id/btn_one"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="24sp"android:text="普通的AlertDialog"/><Buttonandroid:id="@+id/btn_Two"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="24sp"android:text="單選AlertDialog"/><Buttonandroid:id="@+id/btn_three"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="24sp"android:text="單選2AlertDialog"/><Buttonandroid:id="@+id/btn_four"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="24sp"android:text="多選AlertDialog"/><Buttonandroid:id="@+id/btn_five"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="24sp"android:text="適配器AlertDialog"/></LinearLayout>
適配器中的布局 content_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><!-- RelativeLayout 相對布局--><ImageViewandroid:id="@+id/btn_image_view"android:layout_width="50dp"android:layout_height="50dp"android:layout_marginLeft="10dp"/><!-- 標題在圖片的右邊--><TextViewandroid:layout_marginLeft="10dp"android:layout_toRightOf="@+id/btn_image_view"android:id="@+id/btn_title_view"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="22sp"android:textStyle="bold"/><!-- 畫條線在圖片的右邊在文字的下面--><TextViewandroid:id="@+id/btn_tv_line"android:layout_below="@+id/btn_title_view"android:layout_marginLeft="10dp"android:layout_toRightOf="@+id/btn_image_view"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="#ccc"android:minHeight="1dp"android:maxHeight="1dp"/><!-- 內容在圖片的右邊在線的下面--><TextViewandroid:layout_below="@+id/btn_tv_line"android:layout_marginLeft="10dp"android:layout_toRightOf="@+id/btn_image_view"android:id="@+id/btn_tv_content"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="20sp"/><!-- 時間提示在最右邊顯示在父元素內右邊--><TextViewandroid:id="@+id/btn_time"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="20sp"android:layout_alignParentRight="true"/></RelativeLayout>