MaterialDialog.java 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. package com.afollestad.materialdialogs;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.content.DialogInterface;
  5. import android.graphics.Paint;
  6. import android.graphics.Typeface;
  7. import android.graphics.drawable.Drawable;
  8. import android.os.Build;
  9. import android.os.Looper;
  10. import android.support.annotation.ArrayRes;
  11. import android.support.annotation.AttrRes;
  12. import android.support.annotation.ColorRes;
  13. import android.support.annotation.DimenRes;
  14. import android.support.annotation.DrawableRes;
  15. import android.support.annotation.LayoutRes;
  16. import android.support.annotation.NonNull;
  17. import android.support.annotation.Nullable;
  18. import android.support.annotation.StringRes;
  19. import android.support.v4.content.res.ResourcesCompat;
  20. import android.text.TextUtils;
  21. import android.view.LayoutInflater;
  22. import android.view.View;
  23. import android.view.ViewTreeObserver;
  24. import android.view.WindowManager;
  25. import android.widget.AdapterView;
  26. import android.widget.CheckBox;
  27. import android.widget.EditText;
  28. import android.widget.FrameLayout;
  29. import android.widget.ImageView;
  30. import android.widget.LinearLayout;
  31. import android.widget.ListAdapter;
  32. import android.widget.ListView;
  33. import android.widget.ProgressBar;
  34. import android.widget.TextView;
  35. import com.afollestad.materialdialogs.internal.MDButton;
  36. import com.afollestad.materialdialogs.internal.MDRootLayout;
  37. import com.afollestad.materialdialogs.util.DialogUtils;
  38. import com.afollestad.materialdialogs.util.TypefaceHelper;
  39. import java.util.ArrayList;
  40. import java.util.Arrays;
  41. import java.util.Collections;
  42. import java.util.List;
  43. /**
  44. * @author Aidan Follestad (afollestad)
  45. */
  46. public class MaterialDialog extends DialogBase implements
  47. View.OnClickListener, AdapterView.OnItemClickListener {
  48. protected final MDRootLayout view;
  49. protected final Builder mBuilder;
  50. protected ListView listView;
  51. protected ImageView icon;
  52. protected TextView title;
  53. protected View titleFrame;
  54. protected FrameLayout customViewFrame;
  55. protected ProgressBar mProgress;
  56. protected TextView mProgressLabel;
  57. protected TextView mProgressMinMax;
  58. protected TextView content;
  59. protected EditText input;
  60. protected MDButton positiveButton;
  61. protected MDButton neutralButton;
  62. protected MDButton negativeButton;
  63. protected ListType listType;
  64. protected List<Integer> selectedIndicesList;
  65. @SuppressLint("InflateParams")
  66. protected MaterialDialog(Builder builder) {
  67. super(builder.context, DialogInit.getTheme(builder));
  68. mBuilder = builder;
  69. final LayoutInflater inflater = LayoutInflater.from(builder.context);
  70. view = (MDRootLayout) inflater.inflate(DialogInit.getInflateLayout(builder), null);
  71. DialogInit.init(this);
  72. }
  73. protected final void setTypeface(TextView text, Typeface t) {
  74. if (t == null) return;
  75. int flags = text.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG;
  76. text.setPaintFlags(flags);
  77. text.setTypeface(t);
  78. }
  79. protected final void checkIfListInitScroll() {
  80. if (listView == null)
  81. return;
  82. listView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  83. @Override
  84. public void onGlobalLayout() {
  85. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
  86. //noinspection deprecation
  87. listView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
  88. } else {
  89. listView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
  90. }
  91. if (listType == ListType.SINGLE || listType == ListType.MULTI) {
  92. int selectedIndex;
  93. if (listType == ListType.SINGLE) {
  94. if (mBuilder.selectedIndex < 0)
  95. return;
  96. selectedIndex = mBuilder.selectedIndex;
  97. } else {
  98. if (mBuilder.selectedIndices == null || mBuilder.selectedIndices.length == 0)
  99. return;
  100. List<Integer> indicesList = Arrays.asList(mBuilder.selectedIndices);
  101. Collections.sort(indicesList);
  102. selectedIndex = indicesList.get(0);
  103. }
  104. if (listView.getLastVisiblePosition() < selectedIndex) {
  105. final int totalVisible = listView.getLastVisiblePosition() - listView.getFirstVisiblePosition();
  106. // Scroll so that the selected index appears in the middle (vertically) of the ListView
  107. int scrollIndex = selectedIndex - (totalVisible / 2);
  108. if (scrollIndex < 0) scrollIndex = 0;
  109. final int fScrollIndex = scrollIndex;
  110. listView.post(new Runnable() {
  111. @Override
  112. public void run() {
  113. listView.requestFocus();
  114. listView.setSelection(fScrollIndex);
  115. }
  116. });
  117. }
  118. }
  119. }
  120. });
  121. }
  122. /**
  123. * Sets the dialog ListView's adapter and it's item click listener.
  124. */
  125. protected final void invalidateList() {
  126. if ((mBuilder.items == null || mBuilder.items.length == 0) && mBuilder.adapter == null)
  127. return;
  128. // Set up list with adapter
  129. listView.setAdapter(mBuilder.adapter);
  130. if (listType != null || mBuilder.listCallbackCustom != null)
  131. listView.setOnItemClickListener(this);
  132. }
  133. @Override
  134. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  135. if (mBuilder.listCallbackCustom != null) {
  136. // Custom adapter
  137. CharSequence text = null;
  138. if (view instanceof TextView)
  139. text = ((TextView) view).getText();
  140. mBuilder.listCallbackCustom.onSelection(this, view, position, text);
  141. } else if (listType == null || listType == ListType.REGULAR) {
  142. // Default adapter, non choice mode
  143. if (mBuilder.autoDismiss) {
  144. // If auto dismiss is enabled, dismiss the dialog when a list item is selected
  145. dismiss();
  146. }
  147. mBuilder.listCallback.onSelection(this, view, position, mBuilder.items[position]);
  148. } else {
  149. // Default adapter, choice mode
  150. if (listType == ListType.MULTI) {
  151. final boolean shouldBeChecked = !selectedIndicesList.contains(Integer.valueOf(position));
  152. final CheckBox cb = (CheckBox) ((LinearLayout) view).getChildAt(0);
  153. if (shouldBeChecked) {
  154. // Add the selection to the states first so the callback includes it (when alwaysCallMultiChoiceCallback)
  155. selectedIndicesList.add(position);
  156. if (mBuilder.alwaysCallMultiChoiceCallback) {
  157. // If the checkbox wasn't previously selected, and the callback returns true, add it to the states and check it
  158. if (sendMultichoiceCallback()) {
  159. cb.setChecked(true);
  160. } else {
  161. // The callback cancelled selection, remove it from the states
  162. selectedIndicesList.remove(Integer.valueOf(position));
  163. }
  164. } else {
  165. // The callback was not used to check if selection is allowed, just select it
  166. cb.setChecked(true);
  167. }
  168. } else {
  169. // The checkbox was unchecked
  170. selectedIndicesList.remove(Integer.valueOf(position));
  171. cb.setChecked(false);
  172. if (mBuilder.alwaysCallMultiChoiceCallback)
  173. sendMultichoiceCallback();
  174. }
  175. } else if (listType == ListType.SINGLE) {
  176. boolean allowSelection = true;
  177. if (mBuilder.autoDismiss && mBuilder.positiveText == null) {
  178. // If auto dismiss is enabled, and no action button is visible to approve the selection, dismiss the dialog
  179. dismiss();
  180. // Don't allow the selection to be updated since the dialog is being dismissed anyways
  181. allowSelection = false;
  182. // Update selected index and send callback
  183. mBuilder.selectedIndex = position;
  184. sendSingleChoiceCallback(view);
  185. } else if (mBuilder.alwaysCallSingleChoiceCallback) {
  186. int oldSelected = mBuilder.selectedIndex;
  187. // Temporarily set the new index so the callback uses the right one
  188. mBuilder.selectedIndex = position;
  189. // Only allow the radio button to be checked if the callback returns true
  190. allowSelection = sendSingleChoiceCallback(view);
  191. // Restore the old selected index, so the state is updated below
  192. mBuilder.selectedIndex = oldSelected;
  193. }
  194. // Update the checked states
  195. if (allowSelection && mBuilder.selectedIndex != position) {
  196. mBuilder.selectedIndex = position;
  197. ((MaterialDialogAdapter) mBuilder.adapter).notifyDataSetChanged();
  198. }
  199. }
  200. }
  201. }
  202. public static class NotImplementedException extends Error {
  203. public NotImplementedException(@SuppressWarnings("SameParameterValue") String message) {
  204. super(message);
  205. }
  206. }
  207. public static class DialogException extends WindowManager.BadTokenException {
  208. public DialogException(@SuppressWarnings("SameParameterValue") String message) {
  209. super(message);
  210. }
  211. }
  212. protected final Drawable getListSelector() {
  213. if (mBuilder.listSelector != 0)
  214. return ResourcesCompat.getDrawable(mBuilder.context.getResources(), mBuilder.listSelector, null);
  215. final Drawable d = DialogUtils.resolveDrawable(mBuilder.context, R.attr.md_list_selector);
  216. if (d != null) return d;
  217. return DialogUtils.resolveDrawable(getContext(), R.attr.md_list_selector);
  218. }
  219. /* package */ Drawable getButtonSelector(DialogAction which, boolean isStacked) {
  220. if (isStacked) {
  221. if (mBuilder.btnSelectorStacked != 0)
  222. return ResourcesCompat.getDrawable(mBuilder.context.getResources(), mBuilder.btnSelectorStacked, null);
  223. final Drawable d = DialogUtils.resolveDrawable(mBuilder.context, R.attr.md_btn_stacked_selector);
  224. if (d != null) return d;
  225. return DialogUtils.resolveDrawable(getContext(), R.attr.md_btn_stacked_selector);
  226. } else {
  227. switch (which) {
  228. default: {
  229. if (mBuilder.btnSelectorPositive != 0)
  230. return ResourcesCompat.getDrawable(mBuilder.context.getResources(), mBuilder.btnSelectorPositive, null);
  231. final Drawable d = DialogUtils.resolveDrawable(mBuilder.context, R.attr.md_btn_positive_selector);
  232. if (d != null) return d;
  233. return DialogUtils.resolveDrawable(getContext(), R.attr.md_btn_positive_selector);
  234. }
  235. case NEUTRAL: {
  236. if (mBuilder.btnSelectorNeutral != 0)
  237. return ResourcesCompat.getDrawable(mBuilder.context.getResources(), mBuilder.btnSelectorNeutral, null);
  238. final Drawable d = DialogUtils.resolveDrawable(mBuilder.context, R.attr.md_btn_neutral_selector);
  239. if (d != null) return d;
  240. return DialogUtils.resolveDrawable(getContext(), R.attr.md_btn_neutral_selector);
  241. }
  242. case NEGATIVE: {
  243. if (mBuilder.btnSelectorNegative != 0)
  244. return ResourcesCompat.getDrawable(mBuilder.context.getResources(), mBuilder.btnSelectorNegative, null);
  245. final Drawable d = DialogUtils.resolveDrawable(mBuilder.context, R.attr.md_btn_negative_selector);
  246. if (d != null) return d;
  247. return DialogUtils.resolveDrawable(getContext(), R.attr.md_btn_negative_selector);
  248. }
  249. }
  250. }
  251. }
  252. private boolean sendSingleChoiceCallback(View v) {
  253. CharSequence text = null;
  254. if (mBuilder.selectedIndex >= 0) {
  255. text = mBuilder.items[mBuilder.selectedIndex];
  256. }
  257. return mBuilder.listCallbackSingleChoice.onSelection(this, v, mBuilder.selectedIndex, text);
  258. }
  259. private boolean sendMultichoiceCallback() {
  260. Collections.sort(selectedIndicesList); // make sure the indicies are in order
  261. List<CharSequence> selectedTitles = new ArrayList<>();
  262. for (Integer i : selectedIndicesList) {
  263. selectedTitles.add(mBuilder.items[i]);
  264. }
  265. return mBuilder.listCallbackMultiChoice.onSelection(this,
  266. selectedIndicesList.toArray(new Integer[selectedIndicesList.size()]),
  267. selectedTitles.toArray(new CharSequence[selectedTitles.size()]));
  268. }
  269. @Override
  270. public final void onClick(View v) {
  271. DialogAction tag = (DialogAction) v.getTag();
  272. switch (tag) {
  273. case POSITIVE: {
  274. if (mBuilder.callback != null)
  275. mBuilder.callback.onPositive(this);
  276. if (mBuilder.listCallbackSingleChoice != null)
  277. sendSingleChoiceCallback(v);
  278. if (mBuilder.listCallbackMultiChoice != null)
  279. sendMultichoiceCallback();
  280. if (mBuilder.inputCallback != null && input != null)
  281. mBuilder.inputCallback.onInput(this, input.getText());
  282. if (mBuilder.autoDismiss) dismiss();
  283. break;
  284. }
  285. case NEGATIVE: {
  286. if (mBuilder.callback != null)
  287. mBuilder.callback.onNegative(this);
  288. if (mBuilder.autoDismiss) dismiss();
  289. break;
  290. }
  291. case NEUTRAL: {
  292. if (mBuilder.callback != null)
  293. mBuilder.callback.onNeutral(this);
  294. if (mBuilder.autoDismiss) dismiss();
  295. break;
  296. }
  297. }
  298. }
  299. /**
  300. * The class used to construct a MaterialDialog.
  301. */
  302. public static class Builder {
  303. protected final Context context;
  304. protected CharSequence title;
  305. protected GravityEnum titleGravity = GravityEnum.START;
  306. protected GravityEnum contentGravity = GravityEnum.START;
  307. protected GravityEnum btnStackedGravity = GravityEnum.END;
  308. protected GravityEnum itemsGravity = GravityEnum.START;
  309. protected GravityEnum buttonsGravity = GravityEnum.START;
  310. protected int titleColor = -1;
  311. protected int contentColor = -1;
  312. protected CharSequence content;
  313. protected CharSequence[] items;
  314. protected CharSequence positiveText;
  315. protected CharSequence neutralText;
  316. protected CharSequence negativeText;
  317. protected View customView;
  318. protected int widgetColor;
  319. protected int positiveColor;
  320. protected int negativeColor;
  321. protected int neutralColor;
  322. protected ButtonCallback callback;
  323. protected ListCallback listCallback;
  324. protected ListCallbackSingleChoice listCallbackSingleChoice;
  325. protected ListCallbackMultiChoice listCallbackMultiChoice;
  326. protected ListCallback listCallbackCustom;
  327. protected boolean alwaysCallMultiChoiceCallback = false;
  328. protected boolean alwaysCallSingleChoiceCallback = false;
  329. protected Theme theme = Theme.LIGHT;
  330. protected boolean cancelable = true;
  331. protected float contentLineSpacingMultiplier = 1.2f;
  332. protected int selectedIndex = -1;
  333. protected Integer[] selectedIndices = null;
  334. protected boolean autoDismiss = true;
  335. protected Typeface regularFont;
  336. protected Typeface mediumFont;
  337. protected boolean useCustomFonts;
  338. protected Drawable icon;
  339. protected boolean limitIconToDefaultSize;
  340. protected int maxIconSize = -1;
  341. protected ListAdapter adapter;
  342. protected OnDismissListener dismissListener;
  343. protected OnCancelListener cancelListener;
  344. protected OnKeyListener keyListener;
  345. protected OnShowListener showListener;
  346. protected boolean forceStacking;
  347. protected boolean wrapCustomViewInScroll;
  348. protected int dividerColor;
  349. protected int backgroundColor;
  350. protected int itemColor;
  351. protected boolean indeterminateProgress;
  352. protected boolean showMinMax;
  353. protected int progress = -2;
  354. protected int progressMax = 0;
  355. protected CharSequence inputPrefill;
  356. protected CharSequence inputHint;
  357. protected InputCallback inputCallback;
  358. protected boolean titleColorSet = false;
  359. protected boolean contentColorSet = false;
  360. protected boolean itemColorSet = false;
  361. @DrawableRes
  362. protected int listSelector;
  363. @DrawableRes
  364. protected int btnSelectorStacked;
  365. @DrawableRes
  366. protected int btnSelectorPositive;
  367. @DrawableRes
  368. protected int btnSelectorNeutral;
  369. @DrawableRes
  370. protected int btnSelectorNegative;
  371. public final Context getContext() {
  372. return context;
  373. }
  374. public Builder(@NonNull Context context) {
  375. this.context = context;
  376. final int materialBlue = context.getResources().getColor(R.color.md_material_blue_600);
  377. // Retrieve default accent colors, which are used on the action buttons and progress bars
  378. this.widgetColor = DialogUtils.resolveColor(context, R.attr.colorAccent, materialBlue);
  379. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  380. this.widgetColor = DialogUtils.resolveColor(context, android.R.attr.colorAccent, this.widgetColor);
  381. }
  382. this.positiveColor = this.widgetColor;
  383. this.negativeColor = this.widgetColor;
  384. this.neutralColor = this.widgetColor;
  385. // Set the default theme based on the Activity theme's primary color darkness (more white or more black)
  386. final int primaryTextColor = DialogUtils.resolveColor(context, android.R.attr.textColorPrimary);
  387. this.theme = DialogUtils.isColorDark(primaryTextColor) ? Theme.LIGHT : Theme.DARK;
  388. // Load theme values from the ThemeSingleton if needed
  389. checkSingleton();
  390. // Retrieve gravity settings from global theme attributes if needed
  391. this.titleGravity = DialogUtils.resolveGravityEnum(context, R.attr.md_title_gravity, this.titleGravity);
  392. this.contentGravity = DialogUtils.resolveGravityEnum(context, R.attr.md_content_gravity, this.contentGravity);
  393. this.btnStackedGravity = DialogUtils.resolveGravityEnum(context, R.attr.md_btnstacked_gravity, this.btnStackedGravity);
  394. this.itemsGravity = DialogUtils.resolveGravityEnum(context, R.attr.md_items_gravity, this.itemsGravity);
  395. this.buttonsGravity = DialogUtils.resolveGravityEnum(context, R.attr.md_buttons_gravity, this.buttonsGravity);
  396. }
  397. private void checkSingleton() {
  398. if (ThemeSingleton.get(false) == null) return;
  399. ThemeSingleton s = ThemeSingleton.get();
  400. theme(s.darkTheme ? Theme.DARK : Theme.LIGHT);
  401. if (s.titleColor != 0)
  402. this.titleColor = s.titleColor;
  403. if (s.contentColor != 0)
  404. this.contentColor = s.contentColor;
  405. if (s.positiveColor != 0)
  406. this.positiveColor = s.positiveColor;
  407. if (s.neutralColor != 0)
  408. this.neutralColor = s.neutralColor;
  409. if (s.negativeColor != 0)
  410. this.negativeColor = s.negativeColor;
  411. if (s.itemColor != 0)
  412. this.itemColor = s.itemColor;
  413. if (s.icon != null)
  414. this.icon = s.icon;
  415. if (s.backgroundColor != 0)
  416. this.backgroundColor = s.backgroundColor;
  417. if (s.dividerColor != 0)
  418. this.dividerColor = s.dividerColor;
  419. if (s.btnSelectorStacked != 0)
  420. this.btnSelectorStacked = s.btnSelectorStacked;
  421. if (s.listSelector != 0)
  422. this.listSelector = s.listSelector;
  423. if (s.btnSelectorPositive != 0)
  424. this.btnSelectorPositive = s.btnSelectorPositive;
  425. if (s.btnSelectorNeutral != 0)
  426. this.btnSelectorNeutral = s.btnSelectorNeutral;
  427. if (s.btnSelectorNegative != 0)
  428. this.btnSelectorNegative = s.btnSelectorNegative;
  429. if (s.widgetColor != 0)
  430. this.widgetColor = s.widgetColor;
  431. this.titleGravity = s.titleGravity;
  432. this.contentGravity = s.contentGravity;
  433. this.btnStackedGravity = s.btnStackedGravity;
  434. this.itemsGravity = s.itemsGravity;
  435. this.buttonsGravity = s.buttonsGravity;
  436. }
  437. public Builder title(@StringRes int titleRes) {
  438. title(this.context.getString(titleRes));
  439. return this;
  440. }
  441. public Builder title(@NonNull CharSequence title) {
  442. this.title = title;
  443. return this;
  444. }
  445. public Builder titleGravity(@NonNull GravityEnum gravity) {
  446. this.titleGravity = gravity;
  447. return this;
  448. }
  449. public Builder titleColor(int color) {
  450. this.titleColor = color;
  451. this.titleColorSet = true;
  452. return this;
  453. }
  454. public Builder titleColorRes(@ColorRes int colorRes) {
  455. titleColor(this.context.getResources().getColor(colorRes));
  456. return this;
  457. }
  458. public Builder titleColorAttr(@AttrRes int colorAttr) {
  459. titleColor(DialogUtils.resolveColor(this.context, colorAttr));
  460. return this;
  461. }
  462. /**
  463. * Disable usage of the default fonts. This is automatically set by
  464. * {@link #typeface(String, String)} and {@link #typeface(Typeface, Typeface)}.
  465. *
  466. * @return The Builder instance so you can chain calls to it.
  467. */
  468. public Builder disableDefaultFonts() {
  469. this.useCustomFonts = true;
  470. return this;
  471. }
  472. /**
  473. * Sets the fonts used in the dialog. It's recommended that you use {@link #typeface(String, String)} instead,
  474. * to avoid duplicate Typeface allocations and high memory usage.
  475. *
  476. * @param medium The font used on titles and action buttons. Null uses device default.
  477. * @param regular The font used everywhere else, like on the content and list items. Null uses device default.
  478. * @return The Builder instance so you can chain calls to it.
  479. */
  480. public Builder typeface(Typeface medium, Typeface regular) {
  481. this.mediumFont = medium;
  482. this.regularFont = regular;
  483. this.useCustomFonts = true;
  484. return this;
  485. }
  486. /**
  487. * Sets the fonts used in the dialog, by file names. This also uses TypefaceHelper in order
  488. * to avoid any un-needed allocations (it recycles typefaces for you).
  489. *
  490. * @param medium The name of font in assets/fonts, minus the extension (null uses device default). E.g. [your-project]/app/main/assets/fonts/[medium].ttf
  491. * @param regular The name of font in assets/fonts, minus the extension (null uses device default). E.g. [your-project]/app/main/assets/fonts/[regular].ttf
  492. * @return The Builder instance so you can chain calls to it.
  493. */
  494. public Builder typeface(String medium, String regular) {
  495. if (medium != null)
  496. this.mediumFont = TypefaceHelper.get(this.context, medium);
  497. if (regular != null)
  498. this.regularFont = TypefaceHelper.get(this.context, regular);
  499. this.useCustomFonts = true;
  500. return this;
  501. }
  502. public Builder icon(@NonNull Drawable icon) {
  503. this.icon = icon;
  504. return this;
  505. }
  506. public Builder iconRes(@DrawableRes int icon) {
  507. this.icon = ResourcesCompat.getDrawable(context.getResources(), icon, null);
  508. return this;
  509. }
  510. public Builder iconAttr(@AttrRes int iconAttr) {
  511. this.icon = DialogUtils.resolveDrawable(context, iconAttr);
  512. return this;
  513. }
  514. public Builder content(@StringRes int contentRes) {
  515. content(this.context.getString(contentRes));
  516. return this;
  517. }
  518. public Builder content(@NonNull CharSequence content) {
  519. this.content = content;
  520. return this;
  521. }
  522. public Builder content(@StringRes int contentRes, Object... formatArgs) {
  523. content(this.context.getString(contentRes, formatArgs));
  524. return this;
  525. }
  526. public Builder contentColor(int color) {
  527. this.contentColor = color;
  528. this.contentColorSet = true;
  529. return this;
  530. }
  531. public Builder contentColorRes(@ColorRes int colorRes) {
  532. contentColor(this.context.getResources().getColor(colorRes));
  533. return this;
  534. }
  535. public Builder contentColorAttr(@AttrRes int colorAttr) {
  536. contentColor(DialogUtils.resolveColor(this.context, colorAttr));
  537. return this;
  538. }
  539. public Builder contentGravity(@NonNull GravityEnum gravity) {
  540. this.contentGravity = gravity;
  541. return this;
  542. }
  543. public Builder contentLineSpacing(float multiplier) {
  544. this.contentLineSpacingMultiplier = multiplier;
  545. return this;
  546. }
  547. public Builder items(@ArrayRes int itemsRes) {
  548. items(this.context.getResources().getTextArray(itemsRes));
  549. return this;
  550. }
  551. public Builder items(@NonNull CharSequence[] items) {
  552. this.items = items;
  553. return this;
  554. }
  555. public Builder itemsCallback(@NonNull ListCallback callback) {
  556. this.listCallback = callback;
  557. this.listCallbackSingleChoice = null;
  558. this.listCallbackMultiChoice = null;
  559. return this;
  560. }
  561. public Builder itemColor(int color) {
  562. this.itemColor = color;
  563. this.itemColorSet = true;
  564. return this;
  565. }
  566. public Builder itemColorRes(@ColorRes int colorRes) {
  567. return itemColor(this.context.getResources().getColor(colorRes));
  568. }
  569. public Builder itemColorAttr(@AttrRes int colorAttr) {
  570. return itemColor(DialogUtils.resolveColor(this.context, colorAttr));
  571. }
  572. public Builder itemsGravity(@NonNull GravityEnum gravity) {
  573. this.itemsGravity = gravity;
  574. return this;
  575. }
  576. public Builder buttonsGravity(@NonNull GravityEnum gravity) {
  577. this.buttonsGravity = gravity;
  578. return this;
  579. }
  580. /**
  581. * Pass anything below 0 (such as -1) for the selected index to leave all options unselected initially.
  582. * Otherwise pass the index of an item that will be selected initially.
  583. *
  584. * @param selectedIndex The checkbox index that will be selected initially.
  585. * @param callback The callback that will be called when the presses the positive button.
  586. * @return The Builder instance so you can chain calls to it.
  587. */
  588. public Builder itemsCallbackSingleChoice(int selectedIndex, @NonNull ListCallbackSingleChoice callback) {
  589. this.selectedIndex = selectedIndex;
  590. this.listCallback = null;
  591. this.listCallbackSingleChoice = callback;
  592. this.listCallbackMultiChoice = null;
  593. return this;
  594. }
  595. /**
  596. * By default, the single choice callback is only called when the user clicks the positive button
  597. * or if there are no buttons. Call this to force it to always call on item clicks even if the
  598. * positive button exists.
  599. *
  600. * @return The Builder instance so you can chain calls to it.
  601. */
  602. public Builder alwaysCallSingleChoiceCallback() {
  603. this.alwaysCallSingleChoiceCallback = true;
  604. return this;
  605. }
  606. /**
  607. * Pass null for the selected indices to leave all options unselected initially. Otherwise pass
  608. * an array of indices that will be selected initially.
  609. *
  610. * @param selectedIndices The radio button indices that will be selected initially.
  611. * @param callback The callback that will be called when the presses the positive button.
  612. * @return The Builder instance so you can chain calls to it.
  613. */
  614. public Builder itemsCallbackMultiChoice(Integer[] selectedIndices, @NonNull ListCallbackMultiChoice callback) {
  615. this.selectedIndices = selectedIndices;
  616. this.listCallback = null;
  617. this.listCallbackSingleChoice = null;
  618. this.listCallbackMultiChoice = callback;
  619. return this;
  620. }
  621. /**
  622. * By default, the multi choice callback is only called when the user clicks the positive button
  623. * or if there are no buttons. Call this to force it to always call on item clicks even if the
  624. * positive button exists.
  625. *
  626. * @return The Builder instance so you can chain calls to it.
  627. */
  628. public Builder alwaysCallMultiChoiceCallback() {
  629. this.alwaysCallMultiChoiceCallback = true;
  630. return this;
  631. }
  632. public Builder positiveText(@StringRes int postiveRes) {
  633. positiveText(this.context.getString(postiveRes));
  634. return this;
  635. }
  636. public Builder positiveText(@NonNull CharSequence message) {
  637. this.positiveText = message;
  638. return this;
  639. }
  640. public Builder positiveColor(int color) {
  641. this.positiveColor = color;
  642. return this;
  643. }
  644. public Builder positiveColorRes(@ColorRes int colorRes) {
  645. return positiveColor(this.context.getResources().getColor(colorRes));
  646. }
  647. public Builder positiveColorAttr(@AttrRes int colorAttr) {
  648. return positiveColor(DialogUtils.resolveColor(this.context, colorAttr));
  649. }
  650. public Builder neutralText(@StringRes int neutralRes) {
  651. return neutralText(this.context.getString(neutralRes));
  652. }
  653. public Builder neutralText(@NonNull CharSequence message) {
  654. this.neutralText = message;
  655. return this;
  656. }
  657. public Builder negativeColor(int color) {
  658. this.negativeColor = color;
  659. return this;
  660. }
  661. public Builder negativeColorRes(@ColorRes int colorRes) {
  662. return negativeColor(this.context.getResources().getColor(colorRes));
  663. }
  664. public Builder negativeColorAttr(@AttrRes int colorAttr) {
  665. return negativeColor(DialogUtils.resolveColor(this.context, colorAttr));
  666. }
  667. public Builder negativeText(@StringRes int negativeRes) {
  668. return negativeText(this.context.getString(negativeRes));
  669. }
  670. public Builder negativeText(@NonNull CharSequence message) {
  671. this.negativeText = message;
  672. return this;
  673. }
  674. public Builder neutralColor(int color) {
  675. this.neutralColor = color;
  676. return this;
  677. }
  678. public Builder neutralColorRes(@ColorRes int colorRes) {
  679. return neutralColor(this.context.getResources().getColor(colorRes));
  680. }
  681. public Builder neutralColorAttr(@AttrRes int colorAttr) {
  682. return neutralColor(DialogUtils.resolveColor(this.context, colorAttr));
  683. }
  684. public Builder listSelector(@DrawableRes int selectorRes) {
  685. this.listSelector = selectorRes;
  686. return this;
  687. }
  688. public Builder btnSelectorStacked(@DrawableRes int selectorRes) {
  689. this.btnSelectorStacked = selectorRes;
  690. return this;
  691. }
  692. public Builder btnSelector(@DrawableRes int selectorRes) {
  693. this.btnSelectorPositive = selectorRes;
  694. this.btnSelectorNeutral = selectorRes;
  695. this.btnSelectorNegative = selectorRes;
  696. return this;
  697. }
  698. public Builder btnSelector(@DrawableRes int selectorRes, @NonNull DialogAction which) {
  699. switch (which) {
  700. default:
  701. this.btnSelectorPositive = selectorRes;
  702. break;
  703. case NEUTRAL:
  704. this.btnSelectorNeutral = selectorRes;
  705. break;
  706. case NEGATIVE:
  707. this.btnSelectorNegative = selectorRes;
  708. break;
  709. }
  710. return this;
  711. }
  712. /**
  713. * Sets the gravity used for the text in stacked action buttons. By default, it's #{@link GravityEnum#END}.
  714. *
  715. * @param gravity The gravity to use.
  716. * @return The Builder instance so calls can be chained.
  717. */
  718. public Builder btnStackedGravity(@NonNull GravityEnum gravity) {
  719. this.btnStackedGravity = gravity;
  720. return this;
  721. }
  722. public Builder customView(@LayoutRes int layoutRes, boolean wrapInScrollView) {
  723. LayoutInflater li = LayoutInflater.from(this.context);
  724. return customView(li.inflate(layoutRes, null), wrapInScrollView);
  725. }
  726. public Builder customView(@NonNull View view, boolean wrapInScrollView) {
  727. this.customView = view;
  728. this.wrapCustomViewInScroll = wrapInScrollView;
  729. return this;
  730. }
  731. /**
  732. * Makes this dialog a progress dialog.
  733. *
  734. * @param indeterminate If true, an infinite circular spinner is shown. If false, a horizontal progress bar is shown that is incremented or set via the built MaterialDialog instance.
  735. * @param max When indeterminate is false, the max value the horizontal progress bar can get to.
  736. * @return An instance of the Builder so calls can be chained.
  737. */
  738. public Builder progress(boolean indeterminate, int max) {
  739. if (indeterminate) {
  740. this.indeterminateProgress = true;
  741. this.progress = -2;
  742. } else {
  743. this.indeterminateProgress = false;
  744. this.progress = -1;
  745. this.progressMax = max;
  746. }
  747. return this;
  748. }
  749. /**
  750. * Makes this dialog a progress dialog.
  751. *
  752. * @param indeterminate If true, an infinite circular spinner is shown. If false, a horizontal progress bar is shown that is incremented or set via the built MaterialDialog instance.
  753. * @param max When indeterminate is false, the max value the horizontal progress bar can get to.
  754. * @param showMinMax For determinate dialogs, the min and max will be displayed to the left (start) of the progress bar, e.g. 50/100.
  755. * @return An instance of the Builder so calls can be chained.
  756. */
  757. public Builder progress(boolean indeterminate, int max, boolean showMinMax) {
  758. this.showMinMax = showMinMax;
  759. return progress(indeterminate, max);
  760. }
  761. public Builder widgetColor(int color) {
  762. this.widgetColor = color;
  763. return this;
  764. }
  765. public Builder widgetColorRes(@ColorRes int colorRes) {
  766. return widgetColor(this.context.getResources().getColor(colorRes));
  767. }
  768. public Builder widgetColorAttr(@AttrRes int colorAttr) {
  769. return widgetColorRes(DialogUtils.resolveColor(this.context, colorAttr));
  770. }
  771. public Builder dividerColor(int color) {
  772. this.dividerColor = color;
  773. return this;
  774. }
  775. public Builder dividerColorRes(@ColorRes int colorRes) {
  776. return dividerColor(this.context.getResources().getColor(colorRes));
  777. }
  778. public Builder dividerColorAttr(@AttrRes int colorAttr) {
  779. return dividerColor(DialogUtils.resolveColor(this.context, colorAttr));
  780. }
  781. public Builder backgroundColor(int color) {
  782. this.backgroundColor = color;
  783. return this;
  784. }
  785. public Builder backgroundColorRes(@ColorRes int colorRes) {
  786. return backgroundColor(this.context.getResources().getColor(colorRes));
  787. }
  788. public Builder backgroundColorAttr(@AttrRes int colorAttr) {
  789. return backgroundColor(DialogUtils.resolveColor(this.context, colorAttr));
  790. }
  791. public Builder callback(@NonNull ButtonCallback callback) {
  792. this.callback = callback;
  793. return this;
  794. }
  795. public Builder theme(@NonNull Theme theme) {
  796. this.theme = theme;
  797. return this;
  798. }
  799. public Builder cancelable(boolean cancelable) {
  800. this.cancelable = cancelable;
  801. return this;
  802. }
  803. /**
  804. * This defaults to true. If set to false, the dialog will not automatically be dismissed
  805. * when an action button is pressed, and not automatically dismissed when the user selects
  806. * a list item.
  807. *
  808. * @param dismiss Whether or not to dismiss the dialog automatically.
  809. * @return The Builder instance so you can chain calls to it.
  810. */
  811. public Builder autoDismiss(boolean dismiss) {
  812. this.autoDismiss = dismiss;
  813. return this;
  814. }
  815. /**
  816. * Sets a custom {@link android.widget.ListAdapter} for the dialog's list
  817. *
  818. * @param adapter The adapter to set to the list.
  819. * @param callback The callback invoked when an item in the list is selected.
  820. * @return This Builder object to allow for chaining of calls to set methods
  821. */
  822. public Builder adapter(@NonNull ListAdapter adapter, ListCallback callback) {
  823. this.adapter = adapter;
  824. this.listCallbackCustom = callback;
  825. return this;
  826. }
  827. /**
  828. * Limits the display size of a set icon to 48dp.
  829. */
  830. public Builder limitIconToDefaultSize() {
  831. this.limitIconToDefaultSize = true;
  832. return this;
  833. }
  834. public Builder maxIconSize(int maxIconSize) {
  835. this.maxIconSize = maxIconSize;
  836. return this;
  837. }
  838. public Builder maxIconSizeRes(@DimenRes int maxIconSizeRes) {
  839. return maxIconSize((int) this.context.getResources().getDimension(maxIconSizeRes));
  840. }
  841. public Builder showListener(@NonNull OnShowListener listener) {
  842. this.showListener = listener;
  843. return this;
  844. }
  845. public Builder dismissListener(@NonNull OnDismissListener listener) {
  846. this.dismissListener = listener;
  847. return this;
  848. }
  849. public Builder cancelListener(@NonNull OnCancelListener listener) {
  850. this.cancelListener = listener;
  851. return this;
  852. }
  853. public Builder keyListener(@NonNull OnKeyListener listener) {
  854. this.keyListener = listener;
  855. return this;
  856. }
  857. public Builder forceStacking(boolean stacked) {
  858. this.forceStacking = stacked;
  859. return this;
  860. }
  861. public Builder input(CharSequence hint, CharSequence prefill, @NonNull InputCallback callback) {
  862. this.inputCallback = callback;
  863. this.inputHint = hint;
  864. this.inputPrefill = prefill;
  865. return this;
  866. }
  867. public Builder input(@StringRes int hint, @StringRes int prefill, @NonNull InputCallback callback) {
  868. return input(hint == 0 ? null : context.getString(hint), prefill == 0 ? null : context.getString(prefill), callback);
  869. }
  870. public MaterialDialog build() {
  871. return new MaterialDialog(this);
  872. }
  873. public MaterialDialog show() {
  874. MaterialDialog dialog = build();
  875. dialog.show();
  876. return dialog;
  877. }
  878. }
  879. @Override
  880. public void show() {
  881. if (Looper.myLooper() != Looper.getMainLooper())
  882. throw new IllegalStateException("Dialogs can only be shown from the UI thread.");
  883. try {
  884. super.show();
  885. } catch (WindowManager.BadTokenException e) {
  886. throw new DialogException("Bad window token, you cannot show a dialog before an Activity is created or after it's hidden.");
  887. }
  888. }
  889. /**
  890. * Retrieves the view of an action button, allowing you to modify properties such as whether or not it's enabled.
  891. * Use {@link #setActionButton(DialogAction, int)} to change text, since the view returned here is not
  892. * the view that displays text.
  893. *
  894. * @param which The action button of which to get the view for.
  895. * @return The view from the dialog's layout representing this action button.
  896. */
  897. public final View getActionButton(@NonNull DialogAction which) {
  898. switch (which) {
  899. default:
  900. return view.findViewById(R.id.buttonDefaultPositive);
  901. case NEUTRAL:
  902. return view.findViewById(R.id.buttonDefaultNeutral);
  903. case NEGATIVE:
  904. return view.findViewById(R.id.buttonDefaultNegative);
  905. }
  906. }
  907. /*
  908. *//**
  909. * This will not return buttons that are actually in the layout itself, since the layout doesn't
  910. * contain buttons. This is only implemented to avoid crashing issues on Huawei devices. Huawei's
  911. * stock OS requires this method in order to detect visible buttons.
  912. *
  913. * @deprecated Use getActionButton(com.afollestad.materialdialogs.DialogAction)} instead.
  914. *//*
  915. @Deprecated
  916. @Override
  917. public Button getButton(int whichButton) {
  918. Log.w("MaterialDialog", "Warning: getButton() is a deprecated method that does not return valid references to action buttons.");
  919. if (whichButton == AlertDialog.BUTTON_POSITIVE) {
  920. return mBuilder.positiveText != null ? new Button(getContext()) : null;
  921. } else if (whichButton == AlertDialog.BUTTON_NEUTRAL) {
  922. return mBuilder.neutralText != null ? new Button(getContext()) : null;
  923. } else {
  924. return mBuilder.negativeText != null ? new Button(getContext()) : null;
  925. }
  926. }*/
  927. /**
  928. * Retrieves the view representing the dialog as a whole. Be careful with this.
  929. */
  930. public final View getView() {
  931. return view;
  932. }
  933. @Nullable
  934. public final ListView getListView() {
  935. return listView;
  936. }
  937. @Nullable
  938. public final EditText getInputEditText() {
  939. return input;
  940. }
  941. /**
  942. * Retrieves the TextView that contains the dialog title. If you want to update the
  943. * title, use #{@link #setTitle(CharSequence)} instead.
  944. */
  945. public final TextView getTitleView() {
  946. return title;
  947. }
  948. /**
  949. * Retrieves the TextView that contains the dialog content. If you want to update the
  950. * content (message), use #{@link #setContent(CharSequence)} instead.
  951. */
  952. @Nullable
  953. public final TextView getContentView() {
  954. return content;
  955. }
  956. /**
  957. * Retrieves the custom view that was inflated or set to the MaterialDialog during building.
  958. *
  959. * @return The custom view that was passed into the Builder.
  960. */
  961. @Nullable
  962. public final View getCustomView() {
  963. return mBuilder.customView;
  964. }
  965. /**
  966. * Updates an action button's title, causing invalidation to check if the action buttons should be stacked.
  967. * Setting an action button's text to null is a shortcut for hiding it, too.
  968. *
  969. * @param which The action button to update.
  970. * @param title The new title of the action button.
  971. */
  972. public final void setActionButton(@NonNull DialogAction which, CharSequence title) {
  973. switch (which) {
  974. default:
  975. mBuilder.positiveText = title;
  976. positiveButton.setText(title);
  977. positiveButton.setVisibility(title == null ? View.GONE : View.VISIBLE);
  978. break;
  979. case NEUTRAL:
  980. mBuilder.neutralText = title;
  981. neutralButton.setText(title);
  982. neutralButton.setVisibility(title == null ? View.GONE : View.VISIBLE);
  983. break;
  984. case NEGATIVE:
  985. mBuilder.negativeText = title;
  986. negativeButton.setText(title);
  987. negativeButton.setVisibility(title == null ? View.GONE : View.VISIBLE);
  988. break;
  989. }
  990. }
  991. /**
  992. * Updates an action button's title, causing invalidation to check if the action buttons should be stacked.
  993. *
  994. * @param which The action button to update.
  995. * @param titleRes The string resource of the new title of the action button.
  996. */
  997. public final void setActionButton(DialogAction which, @StringRes int titleRes) {
  998. setActionButton(which, getContext().getString(titleRes));
  999. }
  1000. /**
  1001. * Gets whether or not the positive, neutral, or negative action button is visible.
  1002. *
  1003. * @return Whether or not 1 or more action buttons is visible.
  1004. */
  1005. public final boolean hasActionButtons() {
  1006. return numberOfActionButtons() > 0;
  1007. }
  1008. /**
  1009. * Gets the number of visible action buttons.
  1010. *
  1011. * @return 0 through 3, depending on how many should be or are visible.
  1012. */
  1013. public final int numberOfActionButtons() {
  1014. int number = 0;
  1015. if (mBuilder.positiveText != null && positiveButton.getVisibility() == View.VISIBLE)
  1016. number++;
  1017. if (mBuilder.neutralText != null && neutralButton.getVisibility() == View.VISIBLE)
  1018. number++;
  1019. if (mBuilder.negativeText != null && negativeButton.getVisibility() == View.VISIBLE)
  1020. number++;
  1021. return number;
  1022. }
  1023. /**
  1024. * Updates the dialog's title.
  1025. */
  1026. public final void setTitle(@NonNull CharSequence title) {
  1027. this.title.setText(title);
  1028. }
  1029. public void setIcon(@DrawableRes int resId) {
  1030. icon.setImageResource(resId);
  1031. icon.setVisibility(resId != 0 ? View.VISIBLE : View.GONE);
  1032. }
  1033. public void setIcon(Drawable d) {
  1034. icon.setImageDrawable(d);
  1035. icon.setVisibility(d != null ? View.VISIBLE : View.GONE);
  1036. }
  1037. public void setIconAttribute(@AttrRes int attrId) {
  1038. Drawable d = DialogUtils.resolveDrawable(mBuilder.context, attrId);
  1039. icon.setImageDrawable(d);
  1040. icon.setVisibility(d != null ? View.VISIBLE : View.GONE);
  1041. }
  1042. public final void setContent(CharSequence content) {
  1043. this.content.setText(content);
  1044. this.content.setVisibility(TextUtils.isEmpty(content) ? View.GONE : View.VISIBLE);
  1045. }
  1046. /**
  1047. * @deprecated Use setContent() instead.
  1048. */
  1049. @Deprecated
  1050. public void setMessage(CharSequence message) {
  1051. setContent(message);
  1052. }
  1053. public final void setItems(CharSequence[] items) {
  1054. if (mBuilder.adapter == null)
  1055. throw new IllegalStateException("This MaterialDialog instance does not yet have an adapter set to it. You cannot use setItems().");
  1056. if (mBuilder.adapter instanceof MaterialDialogAdapter) {
  1057. mBuilder.adapter = new MaterialDialogAdapter(this,
  1058. ListType.getLayoutForType(listType), R.id.title, items);
  1059. } else {
  1060. throw new IllegalStateException("When using a custom adapter, setItems() cannot be used. Set items through the adapter instead.");
  1061. }
  1062. mBuilder.items = items;
  1063. listView.setAdapter(mBuilder.adapter);
  1064. }
  1065. public final int getCurrentProgress() {
  1066. if (mProgress == null) return -1;
  1067. return mProgress.getProgress();
  1068. }
  1069. public final void incrementProgress(int by) {
  1070. if (mBuilder.progress <= -2)
  1071. throw new IllegalStateException("Cannot use incrementProgress() on this dialog.");
  1072. setProgress(getCurrentProgress() + by);
  1073. }
  1074. public final void setProgress(int progress) {
  1075. if (Looper.myLooper() != Looper.getMainLooper())
  1076. throw new IllegalStateException("You can only set the dialog's progress from the UI thread.");
  1077. else if (mBuilder.progress <= -2)
  1078. throw new IllegalStateException("Cannot use setProgress() on this dialog.");
  1079. mProgress.setProgress(progress);
  1080. int percentage = (int) (((float) getCurrentProgress() / (float) getMaxProgress()) * 100f);
  1081. mProgressLabel.setText(percentage + "%");
  1082. if (mProgressMinMax != null)
  1083. mProgressMinMax.setText(getCurrentProgress() + "/" + getMaxProgress());
  1084. }
  1085. public final void setMaxProgress(int max) {
  1086. if (Looper.myLooper() != Looper.getMainLooper())
  1087. throw new IllegalStateException("You can only set the dialog's progress from the UI thread.");
  1088. else if (mBuilder.progress <= -2)
  1089. throw new IllegalStateException("Cannot use setMaxProgress() on this dialog.");
  1090. mProgress.setMax(max);
  1091. }
  1092. public final boolean isIndeterminateProgress() {
  1093. return mBuilder.indeterminateProgress;
  1094. }
  1095. public final int getMaxProgress() {
  1096. if (mProgress == null) return -1;
  1097. return mProgress.getMax();
  1098. }
  1099. public final boolean isCancelled() {
  1100. return !isShowing();
  1101. }
  1102. /**
  1103. * Convenience method for getting the currently selected index of a single choice list.
  1104. *
  1105. * @return Currently selected index of a single choice list, or -1 if not showing a single choice list
  1106. */
  1107. public int getSelectedIndex() {
  1108. if (mBuilder.listCallbackSingleChoice != null) {
  1109. return mBuilder.selectedIndex;
  1110. } else {
  1111. return -1;
  1112. }
  1113. }
  1114. /**
  1115. * Convenience method for getting the currently selected indices of a multi choice list
  1116. *
  1117. * @return Currently selected index of a multi choice list, or null if not showing a multi choice list
  1118. */
  1119. @Nullable
  1120. public Integer[] getSelectedIndices() {
  1121. if (mBuilder.listCallbackMultiChoice != null) {
  1122. return selectedIndicesList.toArray(new Integer[selectedIndicesList.size()]);
  1123. } else {
  1124. return null;
  1125. }
  1126. }
  1127. /**
  1128. * Convenience method for setting the currently selected index of a single choice list.
  1129. * This only works if you are not using a custom adapter; if you're using a custom adapter,
  1130. * an IllegalStateException is thrown. Note that this does not call the respective single choice callback.
  1131. *
  1132. * @param index The index of the list item to check.
  1133. */
  1134. public void setSelectedIndex(int index) {
  1135. mBuilder.selectedIndex = index;
  1136. if (mBuilder.adapter != null && mBuilder.adapter instanceof MaterialDialogAdapter) {
  1137. ((MaterialDialogAdapter) mBuilder.adapter).notifyDataSetChanged();
  1138. } else {
  1139. throw new IllegalStateException("You can only use setSelectedIndex() with the default adapter implementation.");
  1140. }
  1141. }
  1142. /**
  1143. * Convenience method for setting the currently selected indices of a multi choice list.
  1144. * This only works if you are not using a custom adapter; if you're using a custom adapter,
  1145. * an IllegalStateException is thrown. Note that this does not call the respective multi choice callback.
  1146. *
  1147. * @param indices The indices of the list items to check.
  1148. */
  1149. public void setSelectedIndices(@NonNull Integer[] indices) {
  1150. mBuilder.selectedIndices = indices;
  1151. selectedIndicesList = new ArrayList<>(Arrays.asList(indices));
  1152. if (mBuilder.adapter != null && mBuilder.adapter instanceof MaterialDialogAdapter) {
  1153. ((MaterialDialogAdapter) mBuilder.adapter).notifyDataSetChanged();
  1154. } else {
  1155. throw new IllegalStateException("You can only use setSelectedIndices() with the default adapter implementation.");
  1156. }
  1157. }
  1158. @Override
  1159. public final void onShow(DialogInterface dialog) {
  1160. super.onShow(dialog);
  1161. if (input != null)
  1162. DialogUtils.showKeyboard(this, mBuilder);
  1163. }
  1164. @Override
  1165. protected void onStop() {
  1166. super.onStop();
  1167. if (input != null)
  1168. DialogUtils.hideKeyboard(this, mBuilder);
  1169. }
  1170. protected enum ListType {
  1171. REGULAR, SINGLE, MULTI;
  1172. public static int getLayoutForType(ListType type) {
  1173. switch (type) {
  1174. case REGULAR:
  1175. return R.layout.md_listitem;
  1176. case SINGLE:
  1177. return R.layout.md_listitem_singlechoice;
  1178. case MULTI:
  1179. return R.layout.md_listitem_multichoice;
  1180. default:
  1181. throw new IllegalArgumentException("Not a valid list type");
  1182. }
  1183. }
  1184. }
  1185. /**
  1186. * A callback used for regular list dialogs.
  1187. */
  1188. public interface ListCallback {
  1189. void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text);
  1190. }
  1191. /**
  1192. * A callback used for multi choice (check box) list dialogs.
  1193. */
  1194. public interface ListCallbackSingleChoice {
  1195. /**
  1196. * Return true to allow the radio button to be checked, if the alwaysCallSingleChoice() option is used.
  1197. *
  1198. * @param dialog The dialog of which a list item was selected.
  1199. * @param which The index of the item that was selected.
  1200. * @param text The text of the item that was selected.
  1201. * @return True to allow the radio button to be selected.
  1202. */
  1203. boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text);
  1204. }
  1205. /**
  1206. * A callback used for multi choice (check box) list dialogs.
  1207. */
  1208. public interface ListCallbackMultiChoice {
  1209. /**
  1210. * Return true to allow the check box to be checked, if the alwaysCallSingleChoice() option is used.
  1211. *
  1212. * @param dialog The dialog of which a list item was selected.
  1213. * @param which The indices of the items that were selected.
  1214. * @param text The text of the items that were selected.
  1215. * @return True to allow the checkbox to be selected.
  1216. */
  1217. boolean onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text);
  1218. }
  1219. /**
  1220. * Override these as needed, so no needing to sub empty methods from an interface
  1221. */
  1222. public static abstract class ButtonCallback {
  1223. public void onPositive(MaterialDialog dialog) {
  1224. }
  1225. public void onNegative(MaterialDialog dialog) {
  1226. }
  1227. public void onNeutral(MaterialDialog dialog) {
  1228. }
  1229. public ButtonCallback() {
  1230. super();
  1231. }
  1232. @Override
  1233. protected final Object clone() throws CloneNotSupportedException {
  1234. return super.clone();
  1235. }
  1236. @Override
  1237. public final boolean equals(Object o) {
  1238. return super.equals(o);
  1239. }
  1240. @Override
  1241. protected final void finalize() throws Throwable {
  1242. super.finalize();
  1243. }
  1244. @Override
  1245. public final int hashCode() {
  1246. return super.hashCode();
  1247. }
  1248. @Override
  1249. public final String toString() {
  1250. return super.toString();
  1251. }
  1252. }
  1253. public interface InputCallback {
  1254. void onInput(MaterialDialog dialog, CharSequence input);
  1255. }
  1256. }