# 材料对话框(pre2.0 版本,已弃用) [ ![核心](https://img.shields.io/maven-central/v/com.afollestad.material-dialogs/core?label=core&style=for-the-badge) ](https://repo1.maven.org/maven2/com/afollestad/material-dialogs/core) [ ![公地](https://img.shields.io/maven-central/v/com.afollestad.material-dialogs/commons?label=commons&style=for-the-badge) ](https://repo1.maven.org/maven2/com/afollestad/material-dialogs/commons) [![Build Status](https://travis-ci.org/afollestad/material-dialogs.svg)](https://travis-ci.org/afollestad/material-dialogs) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/0a4acc30a9ce440087f7688735359bb8)](https://www.codacy.com/app/drummeraidan_50/material-dialogs?utm_source=github.com&utm_medium=referral&utm_content=afollestad/material-dialogs&utm_campaign=Badge_Grade) [![GitHub license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/afollestad/material-dialogs/blob/master/LICENSE.txt) ![Screenshots](https://raw.githubusercontent.com/afollestad/material-dialogs/master/art/readmeshowcase.png) # 目录(核心) 1. [样例项目](https://github.com/afollestad/material-dialogs#sample-project) 2. [Gradle 依赖](https://github.com/afollestad/material-dialogs#gradle-dependency)1。[库](https://github.com/afollestad/material-dialogs#repository)2。[Core](https://github.com/afollestad/material-dialogs#core)3。[Commons](https://github.com/afollestad/material-dialogs#commons) 3. [有什么新鲜事吗?](https://github.com/afollestad/material-dialogs#whats-new) 4. [基本对话框](https://github.com/afollestad/material-dialogs#basic-dialog) 5. [取消对话框](https://github.com/afollestad/material-dialogs#dismissing-dialogs) 6. [显示图标](https://github.com/afollestad/material-dialogs#displaying-an-icon) 7. [堆叠动作按钮](https://github.com/afollestad/material-dialogs#stacked-action-buttons)1。[堆叠行为](https://github.com/afollestad/material-dialogs#stacking-behavior) 8. [中性动作按钮](https://github.com/afollestad/material-dialogs#neutral-action-button) 9. [回调](https://github.com/afollestad/material-dialogs#callbacks) 10. [复选框提示](https://github.com/afollestad/material-dialogs#checkbox-prompts) 11. [列出对话框](https://github.com/afollestad/material-dialogs#list-dialogs) 12. [单项选择列表对话框](https://github.com/afollestad/material-dialogs#single-choice-list-dialogs)1。[着色单选按钮](https://github.com/afollestad/material-dialogs#coloring-radio-buttons) 13. [多项选择列表对话框](https://github.com/afollestad/material-dialogs#multi-choice-list-dialogs)1。[着色复选框](https://github.com/afollestad/material-dialogs#coloring-check-boxes) 14. [将 IDS 分配给列表项视图](https://github.com/afollestad/material-dialogs#assigning-ids-to-list-item-views) 15. [自定义列表对话框](https://github.com/afollestad/material-dialogs#custom-list-dialogs) 16. [自定义视图](https://github.com/afollestad/material-dialogs#custom-views)1。[以后的访问](https://github.com/afollestad/material-dialogs#later-access) 17. [字体](https://github.com/afollestad/material-dialogs#typefaces) 18. [获取和设置动作按钮](https://github.com/afollestad/material-dialogs#getting-and-setting-action-buttons) 19. [主题化](https://github.com/afollestad/material-dialogs#theming)1。[基础知识](https://github.com/afollestad/material-dialogs#basics)2。[颜色](https://github.com/afollestad/material-dialogs#colors)3。[选择器](https://github.com/afollestad/material-dialogs#selectors)4。[重力](https://github.com/afollestad/material-dialogs#gravity)5。[材料调色板](https://github.com/afollestad/material-dialogs#material-palette) 20. [全球主题](https://github.com/afollestad/material-dialogs#global-theming) 21. [显示、取消和取消回调](https://github.com/afollestad/material-dialogs#show-cancel-and-dismiss-callbacks) 22. [输入对话框](https://github.com/afollestad/material-dialogs#input-dialogs)1。[为 EditText 着色](https://github.com/afollestad/material-dialogs#coloring-the-edittext)2。[限制输入长度](https://github.com/afollestad/material-dialogs#limiting-input-length)3。[自定义失效](https://github.com/afollestad/material-dialogs#custom-invalidation) 23. [进度对话框](https://github.com/afollestad/material-dialogs#progress-dialogs)1。[ProGuard ](https://github.com/afollestad/material-dialogs#proguard)2。[不确定进度对话框](https://github.com/afollestad/material-dialogs#indeterminate-progress-dialogs)3。[确定进度对话框](https://github.com/afollestad/material-dialogs#determinate-seek-bar-progress-dialogs)4。[在水平方向上创建一个不确定的对话框](https://github.com/afollestad/material-dialogs#make-an-indeterminate-dialog-horizontal)5。[为进度条着色](https://github.com/afollestad/material-dialogs#coloring-the-progress-bar)6。[自定义编号和进度格式](https://github.com/afollestad/material-dialogs#custom-number-and-progress-formats) 24. [Tint Helper ](https://github.com/afollestad/material-dialogs#tint-helper) 25. [Misc ](https://github.com/afollestad/material-dialogs#misc) # 目录(Commons) 1. [颜色选择对话框](https://github.com/afollestad/material-dialogs#color-chooser-dialogs)1。[寻找可见的对话框](https://github.com/afollestad/material-dialogs#finding-visible-dialogs)2。[用户颜色输入](https://github.com/afollestad/material-dialogs#user-color-input) 2. [文件选择器对话框](https://github.com/afollestad/material-dialogs#file-selector-dialogs) 3. [文件夹选择器对话框](https://github.com/afollestad/material-dialogs#folder-selector-dialogs) 4. [偏好对话框](https://github.com/afollestad/material-dialogs#preference-dialogs) 5. [简单列表对话框](https://github.com/afollestad/material-dialogs#simple-list-dialogs) ------ # Sample Project 你可以从这里库下载最新的示例 APK:https://github.com/afollestad/ material-dialogs /blob/master/sample/sample.apk 它也在 Google Play 上: Get it on Google Play 安装示例项目是了解新版本的一个好方法。尽管观看这篇文章库将允许 Github 在我发布新闻稿时给你发电子邮件。 --- # Gradle 依赖 ### Repository Gradle 依赖项可通过 [jCenter](https://bintray.com/drummer-aidan/maven/material-dialogs:core/view) 获得。JCenter 是 Android Studio 使用的默认 Maven库。 此库支持的最小 API 级别是 API14。 ### Core 核心模块包含了这个库的所有主要类,包括 `MaterialDialog`。你可以使用 Core 创建基本的、列表的、单 / 多选择的、进度的、输入的等对话框。 ```gradle dependencies { // ... other dependencies here implementation 'com.afollestad.material-dialogs:core:0.9.6.0' } ``` ### Commons Commons 模块包含对库的扩展,并不是每个人都可能需要。这包括 `ColorChooserDialog`,`FolderChooserDialog`,材料 `Preference` 类,以及 `MaterialSimpleListAdapter`/`materialsimplelistitem`。 ```gradle dependencies { // ... other dependencies here implementation 'com.afollestad.material-dialogs:commons:0.9.6.0' } ``` 新的扩展很可能会在以后添加到 Commons 中。 --- # What's New 请参阅项目的发布页面,获取带有更改日志的版本列表。 ### [View Releases](https://github.com/afollestad/material-dialogs/releases) 如果你看了这个库,每次我发布更新时,GitHub 都会给你发一封电子邮件。 --- # Basic Dialog 首先,注意 `MaterialDialog` 扩展了 `DialogBase`,这扩展了 `android.app.Dialog`。 下面是一个基本的示例,它模仿了你在 Google 的材料设计指南中看到的对话框(这里是:http://www.google.com/design/spec/components/dialogs.html#dialogs-usage)。请注意,对于接受字符串的方法,总是可以用文字字符串和字符串资源代替,对于颜色资源也是一样(例如 `titleColor` 和 `titleColorRes`)。 ```java new MaterialDialog.Builder(this) .title(R.string.title) .content(R.string.content) .positiveText(R.string.agree) .negativeText(R.string.disagree) .show(); ``` 你的活动需要继承 Appcompat 主题,以便正确地处理此库。材质对话框将自动将 `positiveColor`(用于正向操作按钮)与 styles.xml 主题的 `colorAccent` 属性匹配。 如果内容足够长,它将变得可以滚动,并且在操作按钮上方将显示一个分隔符。 --- # 取消对话框 我遇到过很多问题,问你如何拒绝对话。它的工作方式与 `AlertDialog` 相同,因为 `AlertDialog` 和 `MaterialDialog` 都是 `android.app.Dialog` 的实例(这就是 `dismiss()` 和 `show()` 的来源)。不能使用 `Builder` 取消对话框。你只能使用对话框本身来取消对话框。 有很多方法可以得到 `MaterialDialog` 的实例。两种主要的方法是通过 `show()` 和 `build()` 的方法 `MaterialDialog.Builder`。 通过 `show()`,它立即显示对话框并返回可见的对话框: ```java MaterialDialog dialog = new MaterialDialog.Builder(this) .title(R.string.title) .content(R.string.content) .positiveText(R.string.agree) .show(); ``` 通过 `build()`,它只构建对话框,但不显示它,直到你这么说: ```java MaterialDialog.Builder builder = new MaterialDialog.Builder(this) .title(R.string.title) .content(R.string.content) .positiveText(R.string.agree); MaterialDialog dialog = builder.build(); dialog.show(); ``` 一旦显示了对话框,你就可以取消它: ```java dialog.dismiss(); ``` 还有其他不同的地方给出了 `MaterialDialog` 实例,例如在下面的将来部分中讨论的一些回调中。 --- # 显示图标 MaterialDialog 支持显示一个图标,就像 Stock AlertDialog 一样;它将转到标题的左侧。 ```java new MaterialDialog.Builder(this) .title(R.string.title) .content(R.string.content) .positiveText(R.string.agree) .icon(R.drawable.icon) .show(); ``` 你可以使用 `limitIconToDefaultSize()`、`maxIconSize(int size)` 或 `maxIconSizeRes(int sizeRes)`Builder 方法来限制图标的最大大小。 --- # 堆叠动作按钮 如果你有多个动作按钮在一起太宽,不适合在一条线上,对话框将堆叠按钮,以垂直方向。 ```java new MaterialDialog.Builder(this) .title(R.string.title) .content(R.string.content) .positiveText(R.string.longer_positive) .negativeText(R.string.negative) .show(); ``` ### 堆叠行为 你可以从 `Builder` 设置堆叠行为: ```java new MaterialDialog.Builder(this) ... .stackingBehavior(StackingBehavior.ADAPTIVE) // the default value .show(); ``` --- # 中性动作按钮 除了肯定和否定的文本外,你还可以指定中性文本。它将显示最左翼的中立行动。 ```java new MaterialDialog.Builder(this) .title(R.string.title) .content(R.string.content) .positiveText(R.string.agree) .negativeText(R.string.disagree) .neutralText(R.string.more_info) .show(); ``` --- # Callbacks 从 0.8.2.0 版本开始,`callback()`Builder 方法已被弃用,取而代之的是下面讨论的各个回调方法。更早的版本仍然需要使用 `ButtonCallback`。 要知道用户何时选择动作按钮,你需要设置回调: ```java new MaterialDialog.Builder(this) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(MaterialDialog dialog, DialogAction which) { // TODO } }) .onNeutral(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(MaterialDialog dialog, DialogAction which) { // TODO } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(MaterialDialog dialog, DialogAction which) { // TODO } }) .onAny(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(MaterialDialog dialog, DialogAction which) { // TODO } }); ``` 如果你正在监听这三个动作按钮,你可以只使用 `onAny()`。`which` 参数将告诉你按下了哪个按钮。 如果 `autoDismiss` 已关闭,那么你必须手动取消这些回调中的对话框。默认情况下,自动删除是打开的。 --- # 复选框提示 复选框提示允许你显示一个 UI,类似于 Android 在 API23+ 上请求权限时使用的 UI。 注意:你也可以在列表对话框和输入对话框中使用复选框提示。 ```java new MaterialDialog.Builder(this) .iconRes(R.drawable.ic_launcher) .limitIconToDefaultSize() .title(R.string.example_title) .positiveText(R.string.allow) .negativeText(R.string.deny) .onAny(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(MaterialDialog dialog, DialogAction which) { showToast("Prompt checked? " + dialog.isPromptCheckBoxChecked()); } }) .checkBoxPromptRes(R.string.dont_ask_again, false, null) .show(); ``` --- # List Dialogs 创建一个列表对话框只需要传入一个字符串数组。回调(“itemscallback”)也很简单。 ```java new MaterialDialog.Builder(this) .title(R.string.title) .items(R.array.items) .itemsCallback(new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { } }) .show(); ``` 如果 `autoDismiss` 已关闭,则必须手动取消回调中的对话框。默认情况下,自动删除是打开的。你可以将 `positiveText()` 或其他操作按钮传递给构建器,以强制它显示列表下方的操作按钮,但是这仅在某些特定情况下有用。 --- # 单项选择列表对话框 单项选择列表对话框与常规列表对话框几乎相同。唯一的区别是,你使用 `itemsCallbackSingleChoice` 设置回调,而不是 `itemsCallback`。这表示对话框显示列表项旁边的单选按钮。 ```java new MaterialDialog.Builder(this) .title(R.string.title) .items(R.array.items) .itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() { @Override public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { /** * If you use alwaysCallSingleChoiceCallback(), which is discussed below, * returning false here won't allow the newly selected radio button to actually be selected. **/ return true; } }) .positiveText(R.string.choose) .show(); ``` 如果你想预选一个项,请在 `itemsCallbackSingleChoice()` 中传递一个索引 0 或更大的值来代替-1。稍后,如果不使用自定义适配器,则可以在 `MaterialDialog` 实例上使用 `setSelectedIndex(int)` 更新选定的索引。 如果不使用 `positiveText()` 设置正向操作按钮,则当用户按下正向操作按钮时,对话框将自动调用单项选择回调。对话框也会自动删除,除非自动删除被关闭。 如果调用 `alwaysCallSingleChoiceCallback()`,则每当用户选择 / 取消某个项时,都会调用 single choice 回调。 ## 着色单选按钮 与动作按钮和材质对话框中的许多其他元素一样,你可以自定义对话框中单选按钮的颜色。`Builder` 类包含一个 `widgetColor()`、`widgetColorRes()`、`widgetColorAttr()` 和 `choiceWidgetColor()` 方法。它们的名称和参数注释使它们不言自明。 `widgetColor` 是影响其他 UI 元素的相同颜色。`choiceWidgetColor` 是单选和多选对话框特有的,它只影响单选按钮和复选框。你提供的是 `ColorStateList`,而不是用于生成 `ColorStateList` 的单一颜色。 请注意,默认情况下,单选按钮将使用活动主题中的 `colorAccent`(用于 AppCompat)或 `android:colorAccent`(用于材料主题)中的颜色进行着色。 还有一个全局主题化属性,如本文自述的全局主题化部分所示:`md_widget_color`。 --- # 多项选择列表对话框 多项选择列表对话框与常规列表对话框几乎相同。唯一的区别是,你使用 `itemsCallbackMultiChoice` 设置回调,而不是 `itemsCallback`。这表示对话框显示列表项旁边的复选框,回调可以返回多个选择。 ```java new MaterialDialog.Builder(this) .title(R.string.title) .items(R.array.items) .itemsCallbackMultiChoice(null, new MaterialDialog.ListCallbackMultiChoice() { @Override public boolean onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text) { /** * If you use alwaysCallMultiChoiceCallback(), which is discussed below, * returning false here won't allow the newly selected check box to actually be selected * (or the newly unselected check box to be unchecked). * See the limited multi choice dialog example in the sample project for details. **/ return true; } }) .positiveText(R.string.choose) .show(); ``` 如果要预选任何项,请在 `itemsCallbackMultiChoice()` 中传递一个索引(资源或文字)数组来代替 null。稍后,如果不使用自定义适配器,则可以在 `MaterialDialog` 实例上使用 `setSelectedIndices(Integer[])` 更新选定的索引。 如果你没有使用 `positiveText()` 设置一个积极的动作按钮,当用户按下积极的动作按钮时,对话框将自动调用多项选择回调。对话框也会自动删除,除非自动删除被关闭。 如果调用 `alwaysCallMultiChoiceCallback()`,则每当用户选择 / 取消选择一个项时,都会调用多选择回调。 ## 着色复选框 与动作按钮和材质对话框中的许多其他元素一样,你可以自定义对话框复选框的颜色。`Builder` 类包含一个 `widgetColor()`、`widgetColorRes()`、`widgetColorAttr()` 和 `choiceWidgetColor()` 方法。它们的名称和参数注释使它们变得不言自明。 `widgetColor` 是影响其他 UI 元素的相同颜色。`choiceWidgetColor` 是单选和多选对话框特有的,它只影响单选按钮和复选框。你提供的是 `ColorStateList`,而不是用于生成 `ColorStateList` 的单一颜色。 请注意,默认情况下,单选按钮将使用活动主题中的 `colorAccent`(用于 AppCompat)或 `android:colorAccent`(用于材料主题)中的颜色进行着色。 还有一个全局主题化属性,如本文自述的全局主题化部分所示:`md_widget_color`。 --- # 将 IDS 分配给列表项视图 如果需要通过 ID 而不是索引来保留列表项跟踪,则可以从整数数组中分配项目 ID: ```java new MaterialDialog.Builder(this) .title(R.string.socialNetworks) .items(R.array.socialNetworks) .itemsIds(R.array.itemIds) .itemsCallback(new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { Toast.makeText(Activity.this, which + ": " + text + ", ID = " + view.getId(), Toast.LENGTH_SHORT).show(); } }) .show(); ``` 你还可以传递一个字面上的整数数组来代替数组资源 ID。 --- # 自定义列表对话框 与 Android 的本机对话框一样,你也可以通过 `.adapter()` 传入自己的适配器,以定制你希望列表工作的确切方式。 ```java new MaterialDialog.Builder(this) .title(R.string.socialNetworks) // second parameter is an optional layout manager. Must be a LinearLayoutManager or GridLayoutManager. .adapter(new ButtonItemAdapter(this, R.array.socialNetworks), null) .show(); ``` 注意,随着新版本的发布,材质对话框不再支持 `ListView` 和 `ListAdapter`。现在是每个人都使用 `RecyclerView` 的时候了。你的自定义适配器将不得不自行处理项目单击事件;这个库的类和示例项目提供了一些很好的示例,说明如何正确地完成这些操作。 如果需要访问 `RecyclerView`,可以使用 `MaterialDialog` 实例: ```java MaterialDialog dialog = new MaterialDialog.Builder(this) ... .build(); RecyclerView list = dialog.getRecyclerView(); // Do something with it dialog.show(); ``` 请注意,你不需要使用自定义适配器来访问 `RecyclerView`,它可以用于单 / 多选择对话框、常规列表对话框等。 --- # Custom Views 自定义视图非常容易实现。 ```java boolean wrapInScrollView = true; new MaterialDialog.Builder(this) .title(R.string.title) .customView(R.layout.custom_view, wrapInScrollView) .positiveText(R.string.positive) .show(); ``` 如果 `wrapInScrollView` 为真,那么库将把你的自定义视图放入滚动视图中。这允许用户在必要时滚动你的自定义视图(小屏幕、长内容等)。然而,在某些情况下,你并不想要这种行为。这主要包括在自定义布局中使用滚动视图的情况,包括列表视图、recyclerviews、Webviews、Gridviews 等。示例项目包含对此参数同时使用 true 和 false 的示例。 当 `wrapInScrollView` 为真时,你的自定义视图将自动在其周围放置填充。否则,你将负责使用看起来不错的填充值来填充你的内容。 ## Later Access 如果在构建对话框后需要访问自定义视图中的一个视图,则可以使用 `getCustomView()` 的 `MaterialDialog`。如果你将布局资源传递给 `Builder`,这将特别有用,对话框将为你处理视图膨胀。 ```java MaterialDialog dialog = //... initialization via the builder ... View view = dialog.getCustomView(); ``` --- # Typefaces 如果你想使用自定义字体,可以在使用 `Builder` 时调用 `typeface(String, String)`。这将从项目的 `assets/fonts` 文件夹中的文件中提取字体。例如,如果在 `/src/main/assets/fonts` 中有 `Roboto.ttf` 和 `Roboto-Light.ttf`,则将调用 `typeface("Roboto.ttf", "Roboto-Light.ttf")`。此方法还将通过 `TypefaceHelper` 处理回收字体,你可以在自己的项目中使用该方法来避免重复分配。RAW`typeface(Typeface, Typeface)` 变体不会回收字体,每次调用都会重新分配该字体。 还有一个全局主题属性,可以自动将字体应用到应用程序中的每个材料对话框中。 --- # 获取和设置动作按钮 如果你希望在对话框构建和显示之后获得对其中一个对话框操作按钮的引用(例如,启用或禁用按钮): ```java MaterialDialog dialog = //... initialization via the builder ... View negative = dialog.getActionButton(DialogAction.NEGATIVE); View neutral = dialog.getActionButton(DialogAction.NEUTRAL); View positive = dialog.getActionButton(DialogAction.POSITIVE); ``` 如果你想要更新对话框操作按钮的标题(你也可以传递一个字符串资源 ID 来代替文字字符串): ```java MaterialDialog dialog = //... initialization via the builder ... dialog.setActionButton(DialogAction.NEGATIVE, "New Title"); ``` --- # Theming 在棒棒糖之前,如果不使用反射和自定义可拉伸,主题警报对话框基本上是不可能的。自 Kitkat 之后,Android 变得更加中性,但 AlertDialogs 继续使用 Holo Blue 作为标题和标题分隔符。棒棒糖的改进甚至更大,默认情况下,对话框中除了动作按钮外没有其他颜色。这使得主题化变得更加容易。 ## Basics 默认情况下,材质对话框将基于从创建对话框的上下文中检索到的 `?android:textColorPrimary` 属性应用轻主题或暗主题。如果颜色是浅色(例如更白),它会猜测活动使用的是暗主题,它会使用对话框的暗主题。反之亦然的灯光主题。你可以从 `Builder#theme()` 方法手动设置所使用的主题: ```java new MaterialDialog.Builder(this) .content("Hi") .theme(Theme.DARK) .show(); ``` 或者,你也可以使用全局主题化属性,这将在下面的一节中讨论。全局主题避免了为你显示的每个对话框不断调用主题设置器。 ## Colors 用这个库创建的对话框的几乎每个方面都可以着色: ```java new MaterialDialog.Builder(this) .titleColorRes(R.color.material_red_500) .contentColor(Color.WHITE) // notice no 'res' postfix for literal color .linkColorAttr(R.attr.my_link_color_attr) // notice attr is used instead of none or res for attribute resolving .dividerColorRes(R.color.material_pink_500) .backgroundColorRes(R.color.material_blue_grey_800) .positiveColorRes(R.color.material_red_500) .neutralColorRes(R.color.material_red_500) .negativeColorRes(R.color.material_red_500) .widgetColorRes(R.color.material_red_500) .buttonRippleColorRes(R.color.material_red_500) .show(); ``` 这些名字在很大程度上是不言自明的。在本教程的其他章节中讨论的 `widgetColor` 方法适用于进度条、复选框和单选按钮。还需要注意的是,这些方法中的每一种都有 3 种变体,用于直接设置颜色、使用颜色资源和使用颜色属性。 ## Selectors 选择器是当被按下或聚焦时改变状态的可读物。 ```java new MaterialDialog.Builder(this) .btnSelector(R.drawable.custom_btn_selector) .btnSelector(R.drawable.custom_btn_selector_primary, DialogAction.POSITIVE) .btnSelectorStacked(R.drawable.custom_btn_selector_stacked) .listSelector(R.drawable.custom_list_and_stackedbtn_selector) .show(); ``` 第一个 `btnSelector` 行设置了一个可绘制的选择器,用于所有动作按钮。第二个 `btnSelector` 行复写了仅用于正按钮的可画项。这就导致了正向按钮与中性和负向按钮具有不同的选择器。`btnSelectorStacked` 设置一个可拉伸的选择器,当按钮堆叠时使用,要么是因为没有足够的空间将它们全部放在一行上,要么是因为你在 `Builder` 上使用了 `forceStacked(true)`。`listSelector` 用于列表项,当你不使用自定义适配器时。 注: 与使用自定义动作按钮选择器有关的一个重要注意事项:确保你的选择器可拉引用像默认的可拉引用一样插入可拉引用-这对于正确的动作按钮填充很重要。 ## Gravity 你可能不太可能想在对话框中改变元素的重力,但这是有可能的。 ```java new MaterialDialog.Builder(this) .titleGravity(GravityEnum.CENTER) .contentGravity(GravityEnum.CENTER) .btnStackedGravity(GravityEnum.START) .itemsGravity(GravityEnum.END) .buttonsGravity(GravityEnum.END) .show(); ``` 这些都是不言自明的。`titleGravity` 设置对话标题的重力,`contentGravity` 设置对话内容的重力,`btnStackedGravity` 设置堆叠动作按钮的重力,`itemsGravity` 设置列表项的重力(当你不使用自定义适配器时)。 for,`buttonsGravity` 请参见:
START (Default) Neutral Negative Positive
CENTER Negative Neutral Positive
END Positive Negative Neutral
没有正按钮时,负按钮就占了它的位置,只有中间的按钮除外。 ## 材料调色板 要查看适合材料设计调色板的颜色,请参见以下页面:http://www.google.com/design/spec/style/color.html#color-color-palette --- # Global Theming 以上小节中讨论的主题方面的大部分内容都可以自动应用到你在具有包含以下任何属性的主题的活动中显示的所有对话框中: ```xml ``` 动作按钮的颜色也来自于 Material 主题的 `android:colorAccent` 属性,或者 AppCompat Material 主题的 `colorAccent` 属性,如示例项目中所示。手动设置颜色将覆盖该行为。 --- # 显示、取消和取消回调 你可以直接从 `Builder` 而不是在结果 `MaterialDialog` 实例上设置 show/cancel/discound 侦听器。 还要注意,`Builder` 有一个 `cancelable()` 方法,当你在对话框窗口外点击时,可以禁用该对话框。 ```java new MaterialDialog.Builder(this) .title("Use Google's Location Services?") .content("Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running.") .positiveText("Agree") .showListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { } }) .cancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { } }) .dismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { } }) .show(); ``` --- # Input Dialogs 输入对话框很容易解释,它通过输入字段(EditText)从应用程序的用户那里检索输入。如果需要,还可以在 EditText 上面显示内容。 ```java new MaterialDialog.Builder(this) .title(R.string.input) .content(R.string.input_content) .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) .input(R.string.input_hint, R.string.input_prefill, new MaterialDialog.InputCallback() { @Override public void onInput(MaterialDialog dialog, CharSequence input) { // Do something } }).show(); ``` 输入对话框将自动处理对焦 EditText 和显示键盘,以允许用户立即输入。当对话框关闭时,键盘将自动关闭。 请注意,当对话框按下输入时,将强制显示“积极行动”按钮,将输入提交给回调。 还要注意,对 `inputType()` 的调用是可选的。 ## 为 EditText 着色 与动作按钮和材料对话框中的许多其他元素一样,你可以自定义输入对话框 `EditText` 的颜色。`Builder` 类包含一个 `widgetColor()`、`widgetColorRes()` 和 `widgetColorAttr()` 方法。它们的名称和参数注释使它们不言自明。请注意,默认情况下,EditTexts 将使用活动主题中的 `colorAccent`(用于 AppCompat)或 `android:colorAccent`(用于材料主题)中的颜色进行着色。 还有一个全局主题化属性,如本文自述的全局主题化部分所示:`md_widget_color`。 ## 限制输入长度 下面的代码将在输入对话框中显示一个小指示器,告诉用户他们输入了多少字符。如果输入少于 2 个字符或超过 20 个字符,对话框将不允许提交输入。它还将为输入字段和字符计数器着色,以错误的颜色传递给第三个参数。 如果最小长度超过 0,就不会有最小长度。如果你通过-1 的最大长度,将没有最大长度。如果根本不传递第三个参数,它将默认为“材料红色”。 ```java new MaterialDialog.Builder(this) .title(R.string.input) .inputRangeRes(2, 20, R.color.material_red_500) .input(null, null, new MaterialDialog.InputCallback() { @Override public void onInput(MaterialDialog dialog, CharSequence input) { // Do something } }).show(); ``` * 请注意,`inputRangeRes(int, int, int)` 为第三个参数获取一个颜色资源 ID,而 `inputRange(int, int, int)` 为第二个参数获取一个文字颜色整数。你可以使用其中一个,或者使用完全不需要第三个参数的变量。 ## 自定义失效 使输入对话框无效(基于你认为输入是否可接受而启用或禁用 EditText)的最简单方法是从 `Builder` 调用 `alwaysCallInputCallback()`,以便每当用户更改输入时都调用回调。从那里,你可以不断地检查他们输入了什么。如果你决定他们不能提交它,那么你可以在回调中禁用 Submit 按钮: ```java dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false); ``` --- # 进度对话框 这个库允许你显示带有材质设计的进度对话框,甚至可以使用你的应用程序的重音颜色为进度条着色(如果你使用 AppCompat 为你的应用程序或棒棒糖上的材质主题设置主题)。 ## Proguard 通常,`ObjectAnimator` 在它在此库中使用的上下文中(用于自定义进度拖拽)将需要特殊的 ProGuard 规则,以便当你的应用程序构建为发布模式时,某些元素不会被删除。幸运的是,AAR 包可以指定 ProGuard 规则,这些规则被包含在依赖它们的应用程序中。因此,你不必担心包含任何 ProGuard 规则,以确保进度条表现良好。 ## 不确定进度对话框 这将显示带有旋转圆圈的经典进度对话框,请查看示例项目以查看其实际运行情况: ```java new MaterialDialog.Builder(this) .title(R.string.progress_dialog) .content(R.string.please_wait) .progress(true, 0) .show(); ``` ## 确定进度对话框 如果对话框不是不确定的,它会显示一个水平进度条,该进度条会增加到最大值。代码中的注释解释了它的作用。 ```java // Create and show a non-indeterminate dialog with a max value of 150 // If the showMinMax parameter is true, a min/max ratio will be shown to the left of the seek bar. boolean showMinMax = true; MaterialDialog dialog = new MaterialDialog.Builder(this) .title(R.string.progress_dialog) .content(R.string.please_wait) .progress(false, 150, showMinMax) .show(); // Loop until the dialog's progress value reaches the max (150) while (dialog.getCurrentProgress() != dialog.getMaxProgress()) { // If the progress dialog is cancelled (the user closes it before it's done), break the loop if (dialog.isCancelled()) break; // Wait 50 milliseconds to simulate doing work that requires progress try { Thread.sleep(50); } catch (InterruptedException e) { break; } // Increment the dialog's progress by 1 after sleeping for 50ms dialog.incrementProgress(1); } // When the loop exits, set the dialog content to a string that equals "Done" dialog.setContent(getString(R.string.done)); ``` 请参阅此对话框中的示例项目,并添加了线程。 ## 在水平方向上创建一个不确定的对话框 默认情况下,不确定进度对话框使用循环进度指示器。从 `Builder` 中,你可以告诉对话框在显示不确定的进度对话框时需要使用水平指示器: ```java new MaterialDialog.Builder(this) .title(R.string.progress_dialog) .content(R.string.please_wait) .progress(true, 0) .progressIndeterminateStyle(true) .show(); ``` ## 为进度条着色 与动作按钮和材料对话框中的许多其他元素一样,你可以自定义进度对话框中进度条的颜色。`Builder` 类包含一个 `widgetColor()`、`widgetColorRes()` 和 `widgetColorAttr()` 方法。它们的名称和参数注释使它们不言自明。请注意,默认情况下,进度条将使用活动主题中的 `colorAccent`(用于 AppCompat)或 `android:colorAccent`(用于材料主题)中的颜色进行着色。 还有一个全局主题化属性,如本文自述的全局主题化部分所示:`md_widget_color`。 ## 自定义编号和进度格式 与股票 `ProgressDialog` 类似,你可以格式化进度 min/max 数字和确定对话框的百分比指示器。 ```java MaterialDialog dialog = new MaterialDialog.Builder(this) .progress(false, 150, true) ... .progressNumberFormat("%1d/%2d") .progressPercentFormat(NumberFormat.getPercentageInstance()) ... .show(); ``` 上面传递的值是默认值。 --- # Tint Helper 你可以使用 `MDTintHelper` 类来动态地为复选框、单选按钮、编辑文本和进度条着色(以避免在运行时无法更改 `styles.xml`)。它在库中用于动态地为 UI 元素着色,以匹配你的设置 `widgetColor`。 --- # Misc 如果你不希望在按下操作按钮或用户选择列表项时自动取消对话框: ```java MaterialDialog dialog = new MaterialDialog.Builder(this) // ... other initialization .autoDismiss(false) .show(); ``` --- # 颜色选择对话框 构建器是这样使用的: ```java // Pass a context, along with the title of the dialog new ColorChooserDialog.Builder(this, R.string.color_palette) .titleSub(R.string.colors) // title of dialog when viewing shades of a color .accentMode(accent) // when true, will display accent palette instead of primary palette .doneButton(R.string.md_done_label) // changes label of the done button .cancelButton(R.string.md_cancel_label) // changes label of the cancel button .backButton(R.string.md_back_label) // changes label of the back button .preselect(accent ? accentPreselect : primaryPreselect) // optionally preselects a color .dynamicButtonColor(true) // defaults to true, false will disable changing action buttons' color to currently selected color .show(this); // an AppCompatActivity which implements ColorCallback ``` 你在对话框中显示的活动 / 片段必须实现 `ColorCallback`: ```java public class MyActivity implements ColorChooserDialog.ColorCallback { // ... @Override public void onColorSelection(ColorChooserDialog dialog, @ColorInt int color) { // TODO } } ``` --- 如果不想使用内置的主色或重色调色板(由整个材质设计调色板组成),还可以指定要显示的自定义颜色: ```java int[] primary = new int[] { Color.parseColor("#F44336") }; int[][] secondary = new int[][] { new int[] { Color.parseColor("#EF5350"), Color.parseColor("#F44336"), Color.parseColor("#E53935") } }; new ColorChooserDialog.Builder(this, R.string.color_palette) .titleSub(R.string.colors) .customColors(primary, secondary) .show(this); ``` 原色的第一个参数也可以使用一个数组资源,这可以在示例项目中看到。如果你为第二个参数传递 `null`,那么对于顶级颜色将不会显示子级别。 ## 寻找可见的对话框 由于 `ColorChooserDialog` 是 `DialogFragment`,因此它通过其 `FragmentManager` 附加到你的活动 / 片段上。`ColorChooserDialog` 有一个名为 `findVisible(AppCompatActivity, String)` 的实用工具方法,如果有可见的颜色选择器,该方法将找到一个可见的颜色选择器: ```java ColorChooserDialog primary = ColorChooserDialog.findVisible(getSupportFragmentManager(), ColorChooserDialog.TAG_PRIMARY); ColorChooserDialog accent = ColorChooserDialog.findVisible(getSupportFragmentManager(), ColorChooserDialog.TAG_ACCENT); ColorChooserDialog custom = ColorChooserDialog.findVisible(getSupportFragmentManager(), ColorChooserDialog.TAG_CUSTOM); ``` ## 用户颜色输入 默认情况下,颜色选择器对话框允许用户使用 RGB 滑块或十六进制输入字段输入自定义颜色。如果你不希望用户能够使用它,则可以禁用此功能: ```java new ColorChooserDialog.Builder(this, R.string.color_palette) .allowUserColorInput(false) .customButton(R.string.md_custom_label) .presetsButton(R.string.md_presets_label) .show(this); ``` 如果你希望用户能够输入自定义颜色,但不希望他们能够更改透明度(alpha): ```java new ColorChooserDialog.Builder(this, R.string.color_palette) .allowUserColorInputAlpha(false) .customButton(R.string.md_custom_label) .presetsButton(R.string.md_presets_label) .show(this); ``` --- # 偏好对话框 Android 的 `EditTextPreference`、`ListPreference` 和 `MultiSelectListPreference` 允许你将首选项活动的设置与通过键入或选择接收到的用户输入相关联。Material Dialog 包括 `MaterialEditTextPreference`、`MaterialListPreference` 和 `MaterialMultiSelectListPreference` 类,可以在你的首选项 XML 中使用这些类来自动使用 Material-Themed Dialog。有关详细信息,请参见示例项目。 默认情况下,所有这些首选项类将把它们的布局设置为 `R.layout.md_preference_custom`。如果不希望设置默认布局,可以在 XML 中的首选项上提供一个属性: ``` app:useStockLayout="true" ``` --- # 文件选择器对话框 构建器是这样使用的: ```java new FileChooserDialog.Builder(this) .initialPath("/sdcard/Download") // changes initial path, defaults to external storage directory .mimeType("image/*") // Optional MIME type filter .extensionsFilter(".png", ".jpg") // Optional extension filter, will override mimeType() .tag("optional-identifier") .goUpLabel("Up") // custom go up label, default label is "..." .show(this); // an AppCompatActivity which implements FileCallback ``` 你在对话框中显示的活动 / 片段必须实现 `FileCallback`: ```java public class MyActivity implements FileChooserDialog.FileCallback { // ... @Override public void onFileSelection(FileChooserDialog dialog, File file) { // TODO final String tag = dialog.getTag(); // gets tag set from Builder, if you use multiple dialogs } } ``` --- # 文件夹选择器对话框 构建器是这样使用的: ```java // Pass AppCompatActivity which implements FolderCallback new FolderChooserDialog.Builder(this) .chooseButton(R.string.md_choose_label) // changes label of the choose button .initialPath("/sdcard/Download") // changes initial path, defaults to external storage directory .tag("optional-identifier") .goUpLabel("Up") // custom go up label, default label is "..." .show(this); ``` 你在对话框中显示的活动 / 片段必须实现 `FolderCallback`: ```java public class MyActivity implements FolderChooserDialog.FolderCallback { // ... @Override public void onFolderSelection(FolderChooserDialog dialog, File folder) { // TODO final String tag = dialog.getTag(); // gets tag set from Builder, if you use multiple dialogs } } ``` --- 你可以选择允许用户从此对话框创建新的文件夹: ```java new FolderChooserDialog.Builder(this) .chooseButton(R.string.md_choose_label) // changes label of the choose button .initialPath("/sdcard/Download") // changes initial path, defaults to external storage directory .tag("optional-identifier") .allowNewFolder(true, R.string.new_folder) // pass 0 in the second parameter to use default button label .show(this); ``` --- # 简单列表对话框 简单列表对话框是一种特定风格的列表对话框,取自材料设计指南:https://www.google.com/design/spec/components/dialogs.html#dialogs-simple-dialogs 这个库的实现只是一个预先制作的适配器,你可以将其传递给 `MaterialDialog.Builder`。 ```java final MaterialSimpleListAdapter adapter = new MaterialSimpleListAdapter(new MaterialSimpleListAdapter.Callback() { @Override public void onMaterialListItemSelected(MaterialDialog dialog, int index, MaterialSimpleListItem item) { // TODO } }); adapter.add(new MaterialSimpleListItem.Builder(this) .content("username@gmail.com") .icon(R.drawable.ic_account_circle) .backgroundColor(Color.WHITE) .build()); adapter.add(new MaterialSimpleListItem.Builder(this) .content("user02@gmail.com") .icon(R.drawable.ic_account_circle) .backgroundColor(Color.WHITE) .build()); adapter.add(new MaterialSimpleListItem.Builder(this) .content(R.string.add_account) .icon(R.drawable.ic_content_add) .iconPaddingDp(8) .build()); new MaterialDialog.Builder(this) .title(R.string.set_backup) .adapter(adapter, null) .show(); ``` ---