material-dialogs


Source link: https://github.com/afollestad/material-dialogs

Material Dialogs

Core Commons Build Status Codacy Badge GitHub license

Screenshots

Table of Contents (Core)

  1. Sample Project
  2. Gradle Dependency
    1. Repository
    2. Core
    3. Commons
  3. What's New
  4. Basic Dialog
  5. Dismissing Dialogs
  6. Displaying an Icon
  7. Stacked Action Buttons
    1. Stacking Behavior
  8. Neutral Action Button
  9. Callbacks
  10. CheckBox Prompts
  11. List Dialogs
  12. Single Choice List Dialogs
    1. Coloring Radio Buttons
  13. Multi Choice List Dialogs
    1. Coloring Check Boxes
  14. Assigning IDs to List Item Views
  15. Custom List Dialogs
  16. Custom Views
    1. Later Access
  17. Typefaces
  18. Getting and Setting Action Buttons
  19. Theming
    1. Basics
    2. Colors
    3. Selectors
    4. Gravity
    5. Material Palette
  20. Global Theming
  21. Show, Cancel, and Dismiss Callbacks
  22. Input Dialogs
    1. Coloring the EditText
    2. Limiting Input Length
    3. Custom Invalidation
  23. Progress Dialogs
    1. Proguard
    2. Indeterminate Progress Dialogs
    3. Determinate (Seek Bar) Progress Dialogs
    4. Make an Indeterminate Dialog Horizontal
    5. Coloring the Progress Bar
    6. Custom Number and Progress Formats
  24. Tint Helper
  25. Misc

Table of Contents (Commons)

  1. Color Chooser Dialogs
    1. Finding Visible Dialogs
    2. User Color Input
  2. File Selector Dialogs
  3. Folder Selector Dialogs
  4. Preference Dialogs
  5. Simple List Dialogs

Sample Project

You can download the latest sample APK from this repo here: https://github.com/afollestad/material-dialogs/blob/master/sample/sample.apk

It's also on Google Play:

Get it on Google Play

Having the sample project installed is a good way to be notified of new releases. Although Watching this repository will allow GitHub to email you whenever I publish a release.


Gradle Dependency

Repository

The Gradle dependency is available via jCenter. jCenter is the default Maven repository used by Android Studio.

The minimum API level supported by this library is API 14.

Core

The core module contains all the major classes of this library, including MaterialDialog. You can create basic, list, single/multi choice, progress, input, etc. dialogs with core.

dependencies {
 	// ... other dependencies here
  compile 'com.afollestad.material-dialogs:core:0.9.5.0' 
}

Commons

The commons module contains extensions to the library that not everyone may need. This includes the ColorChooserDialog, FolderChooserDialog, the Material Preference classes, and MaterialSimpleListAdapter/MaterialSimpleListItem.

dependencies {

  // ... other dependencies here
  compile 'com.afollestad.material-dialogs:commons:0.9.5.0' 
}

It's likely that new extensions will be added to commons later.


What's New

See the project's Releases page for a list of versions with their changelogs.

View Releases

If you Watch this repository, GitHub will send you an email every time I publish an update.


Basic Dialog

First of all, note that MaterialDialog extends DialogBase, which extends android.app.Dialog.

Here's a basic example that mimics the dialog you see on Google's Material design guidelines (here: http://www.google.com/design/spec/components/dialogs.html#dialogs-usage). Note that you can always substitute literal strings and string resources for methods that take strings, the same goes for color resources (e.g. titleColor and titleColorRes).

new MaterialDialog.Builder(this)

.title(R.string.title)

.content(R.string.content)

.positiveText(R.string.agree)

.negativeText(R.string.disagree)

.show();

Your Activities need to inherit the AppCompat themes in order to work correctly with this library. The Material dialog will automatically match the positiveColor (which is used on the positive action button) to the colorAccent attribute of your styles.xml theme.

If the content is long enough, it will become scrollable and a divider will be displayed above the action buttons.


Dismissing Dialogs

I've had lots of issues asking how you dismiss a dialog. It works the same way that AlertDialog does, as both AlertDialog and MaterialDialog are an instance of android.app.Dialog (which is where dismiss() and show() come from). You cannot dismiss a dialog using it's Builder. You can only dismiss a dialog using the dialog itself.

There's many ways you can get an instance of MaterialDialog. The two major ways are through the show() and build() methods of MaterialDialog.Builder.

Through show(), which immediately shows the dialog and returns the visible dialog:

MaterialDialog dialog = new MaterialDialog.Builder(this)

.title(R.string.title)

.content(R.string.content)

.positiveText(R.string.agree)

.show();

Through build(), which only builds the dialog but doesn't show it until you say so:

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();

Once the dialog is shown, you can dismiss it:

dialog.dismiss();

There are other various places where the MaterialDialog instance is given, such as in some callbacks that are discussed in future sections below.


Displaying an Icon

MaterialDialog supports the display of an icon just like the stock AlertDialog; it will go to the left of the title.

new MaterialDialog.Builder(this)

.title(R.string.title)

.content(R.string.content)

.positiveText(R.string.agree)

.icon(R.drawable.icon)

.show();

You can limit the maximum size of the icon using the limitIconToDefaultSize(), maxIconSize(int size), or maxIconSizeRes(int sizeRes) Builder methods.


Stacked Action Buttons

If you have multiple action buttons that together are too wide to fit on one line, the dialog will stack the buttons to be vertically oriented.

new MaterialDialog.Builder(this)

.title(R.string.title)

.content(R.string.content)

.positiveText(R.string.longer_positive)

.negativeText(R.string.negative)

.show();

Stacking Behavior

You can set stacking behavior from the Builder:

new MaterialDialog.Builder(this)
  ...
  .stackingBehavior(StackingBehavior.ADAPTIVE)  // the default value
  .show();

Neutral Action Button

You can specify neutral text in addition to the positive and negative text. It will show the neutral action on the far left.

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

As of version 0.8.2.0, the callback() Builder method is deprecated in favor of the individual callback methods discussed below. Earlier versions will still require use of ButtonCallback.

To know when the user selects an action button, you set callbacks:

new MaterialDialog.Builder(this)
  .onPositive(new MaterialDialog.SingleButtonCallback() {

@Override

public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

 // TODO

}

  
}
)
  .onNeutral(new MaterialDialog.SingleButtonCallback() {

@Override

public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

 // TODO

}

  
}
)
  .onNegative(new MaterialDialog.SingleButtonCallback() {

@Override

public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

 // TODO

}

  
}
)
  .onAny(new MaterialDialog.SingleButtonCallback() {

@Override

public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

 // TODO

}

  
}
);

If you are listening for all three action buttons, you could just use onAny(). The which (DialogAction) parameter will tell you which button was pressed.

If autoDismiss is turned off, then you must manually dismiss the dialog in these callbacks. Auto dismiss is on by default.


CheckBox Prompts

Checkbox prompts allow you to display a UI similar to what Android uses to ask for a permission on API 23+.

Note: you can use checkbox prompts with list dialogs and input dialogs, too.

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(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

 showToast("Prompt checked? " + dialog.isPromptCheckBoxChecked());

}

  
}
)
  .checkBoxPromptRes(R.string.dont_ask_again, false, null)
  .show();

List Dialogs

Creating a list dialog only requires passing in an array of strings. The callback (itemsCallback) is also very simple.

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();

If autoDismiss is turned off, then you must manually dismiss the dialog in the callback. Auto dismiss is on by default. You can pass positiveText() or the other action buttons to the builder to force it to display the action buttons below your list, however this is only useful in some specific cases.


Single Choice List Dialogs

Single choice list dialogs are almost identical to regular list dialogs. The only difference is that you use itemsCallbackSingleChoice to set a callback rather than itemsCallback. That signals the dialog to display radio buttons next to list items.

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();

If you want to preselect an item, pass an index 0 or greater in place of -1 in itemsCallbackSingleChoice(). Later, you can update the selected index using setSelectedIndex(int) on the MaterialDialog instance, if you're not using a custom adapter.

If you do not set a positive action button using positiveText(), the dialog will automatically call the single choice callback when user presses the positive action button. The dialog will also dismiss itself, unless auto dismiss is turned off.

If you make a call to alwaysCallSingleChoiceCallback(), the single choice callback will be called every time the user selects/unselects an item.

Coloring Radio Buttons

Like action buttons and many other elements of the Material dialog, you can customize the color of a dialog's radio buttons. The Builder class contains a widgetColor(), widgetColorRes(), widgetColorAttr(), and choiceWidgetColor() method. Their names and parameter annotations make them self explanatory.

widgetColor is the same color that affects other UI elements. choiceWidgetColor is specific to single and multiple choice dialogs, it only affects radio buttons and checkboxes. You provide a ColorStateList rather than a single color which is used to generate a ColorStateList.

Note that by default, radio buttons will be colored with the color held in colorAccent (for AppCompat) or android:colorAccent (for the Material theme) in your Activity's theme.

There's also a global theming attribute as shown in the Global Theming section of this README: md_widget_color.


Multi Choice List Dialogs

Multiple choice list dialogs are almost identical to regular list dialogs. The only difference is that you use itemsCallbackMultiChoice to set a callback rather than itemsCallback. That signals the dialog to display check boxes next to list items, and the callback can return multiple selections.

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();

If you want to preselect any items, pass an array of indices (resource or literal) in place of null in itemsCallbackMultiChoice(). Later, you can update the selected indices using setSelectedIndices(Integer[]) on the MaterialDialog instance, if you're not using a custom adapter.

If you do not set a positive action button using positiveText(), the dialog will automatically call the multi choice callback when user presses the positive action button. The dialog will also dismiss itself, unless auto dismiss is turned off.

If you make a call to alwaysCallMultiChoiceCallback(), the multi choice callback will be called every time the user selects/unselects an item.

Coloring Check Boxes

Like action buttons and many other elements of the Material dialog, you can customize the color of a dialog's check boxes. The Builder class contains a widgetColor(), widgetColorRes(), widgetColorAttr(), and choiceWidgetColor() method. Their names and parameter annotations make them self explanatory.

widgetColor is the same color that affects other UI elements. choiceWidgetColor is specific to single and multiple choice dialogs, it only affects radio buttons and checkboxes. You provide a ColorStateList rather than a single color which is used to generate a ColorStateList.

Note that by default, radio buttons will be colored with the color held in colorAccent (for AppCompat) or android:colorAccent (for the Material theme) in your Activity's theme.

There's also a global theming attribute as shown in the Global Theming section of this README: md_widget_color.


Assigning IDs to List Item Views

If you need to keep track of list items by ID rather than index, you can assign item IDs from an integer array:

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();

You can also pass a literal integer array (int[]) in place of an array resource ID.


Custom List Dialogs

Like Android's native dialogs, you can also pass in your own adapter via .adapter() to customize exactly how you want your list to work.

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();

Note that with newer releases, Material Dialogs no longer supports ListView and ListAdapter. It's about time that everyone uses RecyclerView. Your custom adapters will have to handle item click events on their own; this library's classes and sample project have some good examples of how that is done correctly.

If you need access to the RecyclerView, you can use the MaterialDialog instance:

MaterialDialog dialog = new MaterialDialog.Builder(this)

...

.build();
  RecyclerView list = dialog.getRecyclerView();
 // Do something with it  dialog.show();

Note that you don't need to be using a custom adapter in order to access the RecyclerView, it's there for single/multi choice dialogs, regular list dialogs, etc.


Custom Views

Custom views are very easy to implement.

boolean wrapInScrollView = true; new MaterialDialog.Builder(this)

.title(R.string.title)

.customView(R.layout.custom_view, wrapInScrollView)

.positiveText(R.string.positive)

.show();

If wrapInScrollView is true, then the library will place your custom view inside of a ScrollView for you. This allows users to scroll your custom view if necessary (small screens, long content, etc.). However, there are cases when you don't want that behavior. This mostly consists of cases when you'd have a ScrollView in your custom layout, including ListViews, RecyclerViews, WebViews, GridViews, etc. The sample project contains examples of using both true and false for this parameter.

Your custom view will automatically have padding put around it when wrapInScrollView is true. Otherwise you're responsible for using padding values that look good with your content.

Later Access

If you need to access a View in the custom view after the dialog is built, you can use getCustomView() of MaterialDialog. This is especially useful if you pass a layout resource to the Builder, the dialog will handle the view inflation for you.

MaterialDialog dialog = //... initialization via the builder ... View view = dialog.getCustomView();

Typefaces

If you want to use custom fonts, you can make a call to typeface(String, String) when using the Builder. This will pull fonts from files in your project's assets/fonts folder. For example, if you had Roboto.ttf and Roboto-Light.ttf in /src/main/assets/fonts, you would call typeface("Roboto.ttf", "Roboto-Light.ttf"). This method will also handle recycling Typefaces via the TypefaceHelper which you can use in your own project to avoid duplicate allocations. The raw typeface(Typeface, Typeface) variation will not recycle typefaces, every call will allocate the Typeface again.

There's a global theming attribute available to automatically apply fonts to every Material Dialog in your app, also.


Getting and Setting Action Buttons

If you want to get a reference to one of the dialog action buttons after the dialog is built and shown (e.g. to enable or disable buttons):

MaterialDialog dialog = //... initialization via the builder ... View negative = dialog.getActionButton(DialogAction.NEGATIVE);
 View neutral = dialog.getActionButton(DialogAction.NEUTRAL);
 View positive = dialog.getActionButton(DialogAction.POSITIVE);

If you want to update the title of a dialog action button (you can pass a string resource ID in place of the literal string, too):

MaterialDialog dialog = //... initialization via the builder ... dialog.setActionButton(DialogAction.NEGATIVE, "New Title");

Theming

Before Lollipop, theming AlertDialogs was basically impossible without using reflection and custom drawables. Since KitKat, Android became more color neutral but AlertDialogs continued to use Holo Blue for the title and title divider. Lollipop has improved even more, with no colors in the dialog by default other than the action buttons. This library makes theming even easier.

Basics

By default, Material Dialogs will apply a light theme or dark theme based on the ?android:textColorPrimary attribute retrieved from the context creating the dialog. If the color is light (e.g. more white), it will guess the Activity is using a dark theme and it will use the dialog's dark theme. Vice versa for the light theme. You can manually set the theme used from the Builder#theme() method:

new MaterialDialog.Builder(this)

.content("Hi")

.theme(Theme.DARK)

.show();

Or you can use the global theming attribute, which is discussed in the section below. Global theming avoids having to constantly call theme setters for every dialog you show.

Colors

Pretty much every aspect of a dialog created with this library can be colored:

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();

The names are self explanatory for the most part. The widgetColor method, discussed in a few other sections of this tutorial, applies to progress bars, check boxes, and radio buttons. Also note that each

Resources

Kickstarter MVP framework for android projects.

Easily add Portfolio Activity in your android app.

A divider for Android's RecyclerView using RecyclerView.ItemDecoration.

A library which helps to create Retry Policy when using Retrofit 2.0 for API calls.

A TextView component with particle system.

We often use the RecyclerView and the RecyclerView.Adapter for our material design apps. Going from the ListView to RecyclerView, I really missed the setEmptyView() method.

So, I extended the original RecyclerView Adapter to help manage different states in the application. The Adapter, apart from the standard list, supports three different views:

  • Loading View (While Data is being fetched)
  • Empty View (When there is not data)
  • Error View (In case of an error while fetching data)

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes