android自定义对话框

In this tutorial, we’ll be discussing and implementing Custom Alert Dialogs in our Android Application.
We’d discussed Android Alert Dialogs already here.

在本教程中,我们将在Android应用程序中讨论和实现“自定义警报对话框”。
我们已经在这里讨论了Android Alert对话框。

警报对话框 (Alert Dialogs)

Alert Dialogs by default are used to create dialogs with text messages and button actions.
Following are the setter methods that we’d already discussed in the previous tutorial.

默认情况下,“警报对话框”用于创建带有文本消息和按钮操作的对话框。
以下是我们在上一教程中已经讨论过的setter方法。

  • setTitlesetTitle
  • setMessagesetMessage
  • setPositiveButtonsetPositiveButton
  • setNegativeButtonsetNegativeButton
  • setNeutralButtonsetNeutralButton
  • setPositiveButtonIcon/setNegativeButtonIcon/setNeutralButtonIconsetPositiveButtonIcon / setNegativeButtonIcon / setNeutralButtonIcon
  • setCancelablesetCancelable
  • setIconsetIcon
  • setOnDismissListenersetOnDismissListener
  • setItems – shows an array of items in the form of a list inside the alert dialogsetItems –在警报对话框内以列表形式显示项目数组
  • setMultiChoiceItems – Sets a list of items to choose from inside the alert dialogsetMultiChoiceItems –设置要在警报对话框中选择的项目列表
  • setView – Used to set a custom layout view inside the alert dialog.setView –用于在警报对话框中设置自定义布局视图。
  • show()表演()
  • setShowListener() – This is triggered when the alert dialog is displayed on the screen. We can do any dynamic changes in heresetShowListener()–在屏幕上显示警报对话框时触发。 我们可以在这里进行任何动态更改
A ProgressDialog is an AlertDialog with the ProgressBar widget.
ProgressDialog是带有ProgressBar小部件的AlertDialog。

In the following section we’ll create different types of custom alert dialog:

在以下部分中,我们将创建不同类型的自定义警报对话框:

  • With List of Items带项目清单
  • With EditText使用EditText
  • With ImageView使用ImageView
  • With SeekBar与SeekBar
  • With RatingBar有RatingBar

项目结构 (Project Structure)

码 (Code)

The code for the activity_main.xml layout file is given below:

下面给出了activity_main.xml布局文件的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:id="@+id/btnSimpleAlert"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="simpleAlert"android:text="SIMPLE ALERT DIALOG"/><Buttonandroid:id="@+id/btnAlertWithItems"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="withItems"android:text="WITH ITEMS"/><Buttonandroid:id="@+id/btnAlertWithMultiChoiceItems"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="withMultiChoiceItems"android:text="WITH MULTI CHOICE ITEMS"/><Buttonandroid:id="@+id/btnAlertWithEditText"android:layout_width="wrap_content"android:onClick="withEditText"android:layout_height="wrap_content"android:text="WITH EDIT TEXT"/><Buttonandroid:id="@+id/btnAlertWithImageView"android:layout_width="wrap_content"android:onClick="withImageView"android:layout_height="wrap_content"android:text="WITH IMAGE VIEW"/><Buttonandroid:id="@+id/btnAlertWithSeekBar"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="withSeekBar"android:text="WITH SEEK BAR"/><Buttonandroid:id="@+id/btnAlertWithRatingBar"android:layout_width="wrap_content"android:onClick="withRatingBar"android:layout_height="wrap_content"android:text="WITH RATING BAR"/></LinearLayout>

Each of the Buttons would create an AlertDialog. We’ve set the onClick method for each of them which would be defined in the MainActivity.java class.

每个按钮将创建一个AlertDialog。 我们为每个方法都设置了onClick方法,该方法将在MainActivity.java类中定义。

简单警报对话框 (Simple Alert Dialog)

Add the following method(s) to your MainActivity.java:

将以下方法添加到您的MainActivity.java中:

public void simpleAlert(View view) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("Simple Alert");builder.setMessage("We have a message");builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {Toast.makeText(getApplicationContext(),"OK was clicked",Toast.LENGTH_SHORT).show();}});builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {Toast.makeText(getApplicationContext(),android.R.string.no, Toast.LENGTH_SHORT).show();}});builder.setCancelable(false);builder.show();}

This is the simplest form of AlertDialog. Let’s get onto the more interesting ones.

这是AlertDialog的最简单形式。 让我们来看一些更有趣的。

AlertDialog.Builder is used to build the AlertDialog.

AlertDialog.Builder用于构建AlertDialog。

To display the AlertDialog we can alternatively use the following code as well:

要显示AlertDialog,我们也可以使用以下代码:

AlertDialog alertDialog = builder.create();
alertDialog.show();

AlertDialog显示项目列表 (AlertDialog Showing List Of Items)

public void withItems(View view) {final String[] items = {"Apple", "Banana", "Orange", "Grapes"};AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("List of Items").setItems(items, new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {Toast.makeText(getApplicationContext(), items[which] + " is clicked", Toast.LENGTH_SHORT).show();}});builder.setPositiveButton("OK", null);builder.setNegativeButton("CANCEL", null);builder.setNeutralButton("NEUTRAL", null);builder.setPositiveButtonIcon(getResources().getDrawable(android.R.drawable.ic_menu_call, getTheme()));builder.setIcon(getResources().getDrawable(R.drawable.jd, getTheme()));AlertDialog alertDialog = builder.create();alertDialog.show();Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);button.setBackgroundColor(Color.BLACK);button.setPadding(0, 0, 20, 0);button.setTextColor(Color.WHITE);}

In the setItems method we pass the array of strings we want to display.
which argument contains the index of the list item that is clicked.

setItems方法中,我们传递要显示的字符串数组。
which参数包含被单击列表项的索引。

We can customize the Button texts and style by retrieving the Button instances over the alertDialog instance and setting the text color etc.

我们可以通过在alertDialog实例上检索Button实例并设置文本颜色等来自定义Button文本和样式。

colorAccent value defined in the styles.xmlcolorAccent值设置的

具有多个选择列表的AlertDialog (AlertDialog With Multiple Selection List)

public void withMultiChoiceItems(View view) {final String[] items = {"Apple", "Banana", "Orange", "Grapes"};final ArrayList<Integer> selectedList = new ArrayList<>();AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("This is list choice dialog box");builder.setMultiChoiceItems(items, null,new DialogInterface.OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which, boolean isChecked) {if (isChecked) {selectedList.add(which);} else if (selectedList.contains(which)) {selectedList.remove(which);}}});builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {ArrayList<String> selectedStrings = new ArrayList<>();for (int j = 0; j < selectedList.size(); j++) {selectedStrings.add(items[selectedList.get(j)]);}Toast.makeText(getApplicationContext(), "Items selected are: " + Arrays.toString(selectedStrings.toArray()), Toast.LENGTH_SHORT).show();}});builder.show();}

This is a better version of the simple list of items that we saw earlier.
Each of the items in the list has a CheckBoxbeside it. The isChecked boolean value returns the checkBox current state.

这是我们之前看到的简单项目清单的更好版本。
列表中的每个项目旁边都有一个CheckBox 。 isChecked布尔值返回checkBox当前状态。

Once the Button is clicked, we show the list of items that were selected by converting the ArrayList populated of the selectedItems into an Array.

单击“按钮”后,我们将通过将由selectedItems填充的ArrayList转换为Array来显示所选项目的列表。

具有EditText的AlertDialog (AlertDialog With EditText)

Using the setView property we can set a custom view from the layout or do that programmatically as well.
In the below function we've done it programmatically.

使用setView属性,我们可以从布局中设置自定义视图,也可以通过编程方式进行。
在下面的函数中,我们以编程方式完成了此操作。

public void withEditText(View view) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("With Edit Text");final EditText input = new EditText(MainActivity.this);LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);input.setLayoutParams(lp);builder.setView(input);builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Toast.makeText(getApplicationContext(), "Text entered is " + input.getText().toString(), Toast.LENGTH_SHORT).show();}});builder.show();}

使用ImageView的警报对话框 (Alert Dialog With ImageView)

Here we'll inflate a custom layout inside our setView method.
Following is the layout that'll be shown inside the AlertDialog:

在这里,我们将在setView方法中setView自定义布局。
以下是将在AlertDialog中显示的布局:

alert_dialog_with_imageview.xml

alert_dialog_with_imageview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:id="@+id/imageView"android:layout_width="wrap_content"android:layout_height="350dp"android:scaleType="centerCrop"android:adjustViewBounds="true"android:src="@drawable/sample"/></LinearLayout>

Add the following function inside your MainActivity.java class:

在MainActivity.java类中添加以下函数:

public void withImageView(View view) {AlertDialog.Builder builder = new AlertDialog.Builder(this);LayoutInflater inflater = getLayoutInflater();View dialogLayout = inflater.inflate(R.layout.alert_dialog_with_imageview, null);builder.setPositiveButton("OK", null);builder.setView(dialogLayout);builder.show();}

带有搜索栏的警报对话框 (Alert Dialog With Seekbar)

public void withSeekBar(View view) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle("With SeekBar");final SeekBar seekBar = new SeekBar(MainActivity.this);LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);seekBar.setLayoutParams(lp);builder.setView(seekBar);builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Toast.makeText(getApplicationContext(), "Progress is " + seekBar.getProgress(), Toast.LENGTH_SHORT).show();}});builder.show();}

On clicking the Button we show the progress value of the SeekBar.

单击按钮后,我们将显示SeekBar的进度值。

带等级栏的警报对话框 (Alert Dialog With Rating Bar)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><RatingBarandroid:id="@+id/ratingBar"android:layout_gravity="center"android:layout_width="wrap_content"android:layout_height="wrap_content"android:numStars="5"android:stepSize="0.5" /></LinearLayout>
public void withRatingBar(View view) {AlertDialog.Builder builder = new AlertDialog.Builder(this);LayoutInflater inflater = getLayoutInflater();builder.setTitle("With RatingBar");View dialogLayout = inflater.inflate(R.layout.alert_dialog_with_ratingbar, null);final RatingBar ratingBar = dialogLayout.findViewById(R.id.ratingBar);builder.setView(dialogLayout);builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Toast.makeText(getApplicationContext(), "Rating is " + ratingBar.getRating(), Toast.LENGTH_SHORT).show();}});builder.show();}

Once you've added all the above methods inside the MainActivity.java class let's build and run our application. Following is the output of the above application in action.

在MainActivity.java类中添加了上述所有方法之后,就可以构建并运行我们的应用程序。 以下是上述应用程序的输出。

This brings an end to this tutorial. You can download the project from the link below:

本教程到此结束。 您可以从下面的链接下载项目:

AndroidCustomAlertDialogAndroidCustomAlertDialog
AndroidCustomAlertDialogAndroidCustomAlertDialog

翻译自: https://www.journaldev.com/22153/android-custom-alert-dialog

android自定义对话框

android自定义对话框_Android自定义提醒对话框相关推荐

  1. java web自定义监听器_Android自定义监听器Listener(自定义Java Callback回调事件)

    Callback回调事件介绍 Java或Android中创建异步回调最普遍的做法就是使用listener监听器或者observer观察者模式来解决,listener回调事件通常用于实现一个代码去监听另 ...

  2. android 自定义键盘_Android自定义输入车牌号键盘、车牌简称,数字 ,字母键盘...

    本文来自阿钟的投稿,全文阅读大约十分钟 为了便于用户快捷的输入车牌号码便需要自定义个车牌键盘,而不是使用系统的键盘输入,上效果图: 横屏效果 图片 竖屏效果 图片 一.首先我们要来分析一下需要做哪些东 ...

  3. android java 圆角_Android自定义View实现带4圆角或者2圆角的效果

    1 问题 实现任意view经过自定义带4圆角或者2圆角的效果 2 原理 1) 实现view 4圆角 我们只需要把左边的图嵌入到右边里面去,最终显示左边的图就行. 2) 实现view上2圆角 我们只需要 ...

  4. android 自定义字体_Android自定义字体教程

    android 自定义字体 In this tutorial, we'll explain how to set up android custom fonts in TextViews and Bu ...

  5. android 斜线 绘制_Android 自定义 斜线进度框 ,雨点式背景

    import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; impor ...

  6. 农历 Android Java 节气_Android自定义日历,可以点击、标注日期、节气、旧历等

    /****************从此出开始将代码拷贝到一个文件中*******************/package cc.util.android.view; import java.text. ...

  7. android 单选框 icon,Android中的普通对话框、单选对话框、多选对话框、带Icon的对话框、以及自定义Adapter和自定义View对话框详解...

    标签: 对话框就是一个AlertDialog,但是一个简单的AlertDialog,我们却可以将它玩出许多花样来,下面我们就来一起总结一下AlertDialog的用法.看看各位童鞋在平时的工作中否都用 ...

  8. android 之Dialog的多种Dialog对话框(以及反射在自定义对话框的运用)

    实际效果: 实例代码: 一个"启动初始Activity.xml" 一个弹出的Activity 业务逻辑代码: package com.hsj.example.alertdialog ...

  9. android 获取对话框对象,Android 基本Dialog和自定义Dialog

    Android 基本Dialog和自定义Dialog Dialog类是对话框的基类,但你应该避免直接实例化Dialog ,可以使用子类 1.AlertDialog 此对话框可以显示标题,最多三个按钮, ...

最新文章

  1. Java中实现多线程关键词整理
  2. eclipse hibernate配置文件(*.hbm.xml)加上自动提示功能
  3. angular分页插件tm.pagination
  4. java 对称的二叉树
  5. C语言简单题-求整数序列中出现次数最多的数
  6. 好程序员技术文档HTML5开发中的javascript闭包
  7. 实现spring mvc流程
  8. springboot项目层次结构_Springboot项目结构Springboot项目结构
  9. 网络管理软件免费linux,SugarNMSTool免费版
  10. android下载https文件,如何通过ssl(https)在android上下载文件
  11. 股票---- 资金在线-个股资金流向与大单分析系统
  12. 区块链报告会心得体会3000_学习区块链的心得体会?
  13. java+selenium简单使用给斗鱼主播刷弹幕-.-
  14. 福建中医药大学数字化校园应用及数据容灾系统181万
  15. SMTP判断邮箱是否存在 检查email地址是否真实存在
  16. 慕课学习史上最全零基础入门HTML5和CSS笔记
  17. Combo Box (组合框)控件的使用方法
  18. python槽怎么用_PyQt4信号与槽详解
  19. np.title函数作用
  20. sqli-labs全通关payload

热门文章

  1. [转]导出数据到Excel的几种方法
  2. 睡前1分钟 坚持瘦下来(信不信由你)
  3. [转载] Python字典中items()和iteritems()区别
  4. 创建型模式之单例模式
  5. 为什么default package包里面的方法不能被其他包调用
  6. gitlab git 安装
  7. 通过宝塔webhook,实现git自动拉取服务器代码
  8. JS_模拟广告栏跟随效果
  9. dwr运行时出现Servlet.init() for servlet dwr-invoker threw exception的解决方法
  10. C++中数字与字符串之间的转换