Android : AlertDialog对话框、单选、多选、适配器-简单应用

news2024/9/17 8:47:49

示例图:

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;

    @Override
    protected 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);
    }

    @Override
    public void onClick(View v) {

        if(v.getId() == R.id.btn_one){
            //普通对话框
            builder = new AlertDialog.Builder(context);
            //标题
            builder.setTitle("游戏提示:");
            //logo
            builder.setIcon(R.mipmap.a);
            //内容
            builder.setMessage("您确认要开始游戏吗?");
            //确定按钮
            builder.setPositiveButton("开始", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(context ,"开始游戏",Toast.LENGTH_SHORT).show();
                }
            });
            //取消按钮  null 表示什么都不做
            builder.setNegativeButton("取消",null);
            //中立按钮
            builder.setNeutralButton("中立", new DialogInterface.OnClickListener() {
                @Override
                public 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() {
                @Override
                public 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);
            //数据源 2
            final String[] arr = new String[]{"java","php","android","c++"};

            //标题
            builder.setTitle("请选择课程:");
            //图标
            builder.setIcon(R.mipmap.a);

            //内容   默认选择项 -1表示不选择  0表示选中第一个
            builder.setSingleChoiceItems(arr, -1, new DialogInterface.OnClickListener() {
                @Override
                public 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() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    if(isChecked){
                        datas.add(arr[which]);
                    }else{
                        datas.remove(arr[which]);
                    }
                }
            });

            //确定按钮 setPositiveButton
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public 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("**通讯信息**");
        //logo
        builder.setIcon(R.mipmap.a);

        //设置数据源  List<? extends Map<String, ?>> data
        List<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]);

            //添加到List
            datas.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() {
            @Override
            public 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">

    <TextView
        android:id="@+id/btn_tv"
        android:text="您选择了:"
        android:textSize="24sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btn_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="普通的AlertDialog"
        />

    <Button
        android:id="@+id/btn_Two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="单选AlertDialog"
        />

    <Button
        android:id="@+id/btn_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="单选2AlertDialog"
        />

    <Button
        android:id="@+id/btn_four"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="多选AlertDialog"
        />

    <Button
        android: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 相对布局-->
    <ImageView
        android:id="@+id/btn_image_view"
        android:layout_width="50dp"
        android:layout_height="50dp"

        android:layout_marginLeft="10dp"
        />

    <!-- 标题
    在图片的右边
    -->
    <TextView
        android: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"
        />

    <!-- 画条线
    在图片的右边
    在文字的下面
    -->
    <TextView
        android: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"
        />
    <!-- 内容
    在图片的右边
    在线的下面
    -->
    <TextView
        android: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"

        />
    <!-- 时间提示
    在最右边显示
    在父元素内右边
    -->
    <TextView
        android:id="@+id/btn_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_alignParentRight="true"
        />

</RelativeLayout>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1245882.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

windows11上安装WSL

Windows电脑上要配置linux&#xff08;这里指ubuntu&#xff09;开发环境&#xff0c;主要有三种方式&#xff1a; 1&#xff09;在windows上装个虚拟机&#xff08;比如vmware&#xff09;。缺点是vmware加载ubuntu后系统会变慢很多&#xff0c;而且需要通过samba来实现window…

电线电缆、漆包线工厂开源MES/生产管理系统/云MES

万界星空科技专业的漆包线MES系统功能介绍&#xff1a; 从原材料出入库-拉丝机等设备管理-漆包线称重打印系统自动入库&#xff08;支持多台秤同时称重&#xff09;-建立销售报价、销售订单-生产订单-支持扫码出库及自动拣货出库-应收应付账款-对接各种其他系统及财务系统。 …

内网穿透的应用-如何在本地安装Flask,以及将其web界面发布到公网上并进行远程访问

轻量级web开发框架&#xff1a;Flask本地部署及实现公网访问界面 文章目录 轻量级web开发框架&#xff1a;Flask本地部署及实现公网访问界面前言1. 安装部署Flask2. 安装Cpolar内网穿透3. 配置Flask的web界面公网访问地址4. 公网远程访问Flask的web界面 前言 本篇文章讲解如何…

qgis添加arcgis的mapserver

左侧浏览器-ArcGIS地图服务器-右键-新建连接 Folder: / 展开-双击图层即可

电脑软件:SmartSystemMenu(窗口置顶工具)介绍

目录 一、软件介绍 二、软件用途 三、安装教程 注意事项 四、功能介绍 五、软件设置 六、软件下载 一、软件介绍 SmartSystemMenu 是一款简单实用的 Windows 窗口增强工具&#xff0c;它可以为窗口的标题栏右键菜单新增 17 个新功能。 二、软件用途 SmartSystemMenu(窗口…

微信小程序完整实现微信支付功能(SpringBoot和小程序)

1.前言 不久前给公司实现支付功能&#xff0c;折腾了一阵子&#xff0c;终于实现了&#xff0c;微信支付对于小白来说真的很困难&#xff0c;特别是没有接触过企业级别开发的大学生更不用说&#xff0c;因此尝试写一篇我如何从小白实现微信小程序支付功能的吧&#xff0c;使用…

智能医疗越发周到!新的机器人系统评估中风后的活动能力

原创 | 文 BFT机器人 中风是在医疗界上最难的解决的病例之一&#xff0c;全球每年有超过1500万人中风&#xff0c;四分之三的中风患者的手臂和手部会出现损伤、虚弱和瘫痪。 许多中风患者日常生活是依靠他们强壮的手臂来完成的&#xff0c;从拿一些小东西到梳头&#xff0c;即…

python 如何利用everything的能力快速搜索兴趣文档

演示代码 # -*- coding:UTF-8 -*- """ author: dyy contact: douyaoyuan126.com time: 2023/11/23 17:10 file: python 如何通过everything搜索兴趣文档.py desc: xxxxxx """# region 引入必要的依赖 import os模块名 DebugInfo try:from Debu…

一些好用的前端小插件(转自知乎)

一些好用的前端小插件&#xff08;2&#xff09; 1. cropper.js Cropper.js 2.0 是一系列用于图像裁剪的 Web 组件。 官网地址&#xff1a;https://fengyuanchen.github.io/cropperjs/v2/zh/ 2. Vditor Vditor是一款浏览器端的 Markdown 编辑器&#xff0c;支持所见即所得、…

【C++】标准模板库STL作业(其二)

&#x1f383;个人专栏&#xff1a; &#x1f42c; 算法设计与分析&#xff1a;算法设计与分析_IT闫的博客-CSDN博客 &#x1f433;Java基础&#xff1a;Java基础_IT闫的博客-CSDN博客 &#x1f40b;c语言&#xff1a;c语言_IT闫的博客-CSDN博客 &#x1f41f;MySQL&#xff1a…

了解销售管理系统,看这篇就够了

在充满活力的现代商业环境中&#xff0c;高效的销售管理是成功的关键。 本文将全面介绍销售管理系统 及其对销售流程的变革性影响。 从潜在客户开发和机会管理到分析驱动的决策&#xff0c;销售管理系统旨在为销售团队提供提高生产力和绩效的工具。 本文分为销售管理系统的概念…

在springboot中实现WebSocket协议通信

前面介绍了使用netty实现websocket通信&#xff0c;有些时候&#xff0c;如果我们的服务并不复杂或者连接数并不高&#xff0c;单独搭建一个websocket服务端有些浪费资源&#xff0c;这时候我们就可以在web服务内提供简单的websocket连接支持。其实springboot已经支持了websock…

通俗理解词向量模型,预训练模型,Transfomer,Bert和GPT的发展脉络和如何实践

最近研究GPT&#xff0c;深入的从transfomer的原理和代码看来一下&#xff0c;现在把学习的资料和自己的理解整理一下。 这个文章写的很通俗易懂&#xff0c;把transformer的来龙去脉&#xff0c;还举例了很多不错的例子。 Transformer通俗笔记&#xff1a;从Word2Vec、Seq2S…

解决PDF预览时,电子签章、日期等不显示问题

文章目录 问题描述问题排查问题解决 问题描述 在预览PDF时&#xff0c;部分签章或控件没有显示。如下图&#xff1a; 正确应该要这样&#xff1a; 问题排查 根据网上搜索&#xff0c;排查&#xff0c;我先看看&#xff0c;pdf.worker.js 里的这三行代码&#xff0c;是否已经注…

MySQL-02-InnoDB存储引擎

实际的业务系统开发中&#xff0c;使用MySQL数据库&#xff0c;我们使用最多的当然是支持事务并发的InnoDB存储引擎的这种表结构&#xff0c;下面我们介绍下InnoDB存储引擎相关的知识点。 1-Innodb体系架构 InnoDB存储引擎有多个内存块&#xff0c;可以认为这些内存块组成了一…

error: ‘for‘ loop initial declarations are only allowed in C99 or C11 mode

在使用for循环时&#xff0c;在循环内定义变量&#xff0c;出现如下错误 [Error] ‘for’ loop initial declarations are only allowed in C99 or C11 mode [Note] use option -stdc99&#xff0c;-stdgnu99&#xff0c;-stdc11 or-stdgnu11 to compile your code 出现这个错误…

22款奔驰S400L升级原厂360全景影像 高清环绕 无死角

360全景影像影像系统提升行车时的便利&#xff0c;不管是新手或是老司机都将是一个不错的配置&#xff0c;无论是在倒车&#xff0c;挪车以及拐弯转角的时候都能及时关注车辆所处的环境状况&#xff0c;避免盲区事故发生&#xff0c;提升行车出入安全性。 360全景影像包含&…

2015年8月19日 Go生态洞察:Go 1.5版本发布

&#x1f337;&#x1f341; 博主猫头虎&#xff08;&#x1f405;&#x1f43e;&#xff09;带您 Go to New World✨&#x1f341; &#x1f984; 博客首页——&#x1f405;&#x1f43e;猫头虎的博客&#x1f390; &#x1f433; 《面试题大全专栏》 &#x1f995; 文章图文…

【C++】内存管理(new与delete)

&#x1f440;樊梓慕&#xff1a;个人主页 &#x1f3a5;个人专栏&#xff1a;《C语言》《数据结构》《蓝桥杯试题》《LeetCode刷题笔记》《实训项目》《C》 &#x1f31d;每一个不曾起舞的日子&#xff0c;都是对生命的辜负 前言 本篇文章我们一起来学习C的内存管理方式&…