Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Xamarin Forms library for implementing Material Design

License

NotificationsYou must be signed in to change notification settings

Baseflow/XF-Material-Library

XF.Material Library

NuGetBuild status

A Xamarin.Forms library for Xamarin.Android and Xamarin.iOS to implementGoogle's Material Design.

Support

  • Feel free to open an issue. Make sure to use one of the templates!
  • Commercial support is available. Integration with your app or services, samples, feature request, etc. Email:hello@baseflow.com
  • Powered by:baseflow.com

Contents

Getting Started

  1. Download the current version throughNuGet and install it in your Xamarin.Forms projects.
  2. Call theMaterial.Init() method in each project:
//Xamarin.FormspublicApp(){this.InitializeComponent();XF.Material.Forms.Material.Init(this);}//Xamarin.AndroidprotectedoverridevoidOnCreate(BundlesavedInstanceState){TabLayoutResource=Resource.Layout.Tabbar;ToolbarResource=Resource.Layout.Toolbar;base.OnCreate(savedInstanceState);Xamarin.Forms.Forms.Init(this,savedInstanceState);XF.Material.Droid.Material.Init(this,savedInstanceState);this.LoadApplication(newApp());}//Xamarin.iOSpublicoverrideboolFinishedLaunching(UIApplicationapp,NSDictionaryoptions){Xamarin.Forms.Forms.Init();XF.Material.iOS.Material.Init();this.LoadApplication(newApp());returnbase.FinishedLaunching(app,options);}
  1. Configure your application's color and font resources. Read more about ithere.

Additional configuration for iOS

In order to be able to change the status bar's colors usingthis or by setting your app colorshere, add this to yourinfo.plist file:

<key>UIViewControllerBasedStatusBarAppearance</key><false/>

Note: If some of the controls like progressbar, checkbox and radio buttons are not showing in iOS then add all the files fromhere to iOS project's Resources folder.

Features

Material UI

Under theXF.Material.Forms.UI namespace, the library offers a number of controls available.

App Bar Customization

You can customize the appearance of the App Bar by using theMaterialNavigationPage control.

CodeAndroidiOS
<ContentPage .... xmlns:material="clr-namespace:XF.Material.Forms.UI;assembly=XF.Material" material:MaterialNavigationPage.AppBarColor="#2c3e50" material:MaterialNavigationPage.AppBarTitleTextFontFamily="Roboto" material:MaterialNavigationPage.AppBarTitleTextFontSize="14" material:MaterialNavigationPage.StatusBarColor="#1B3147" material:MaterialNavigationPage.AppBarTitleTextAlignment="Start" /* Content goes here * </ ContentPage>Android cardiOS card
Attached Properties

These are attached properties that can be used on pages that are navigated through theMaterialNavigationPage control.

  1. AppBarColor - The color of the app bar.

  2. AppBarTitleTextAlignment - The text alignment of the app bar title. The default value isTextAlignment.Start.

  3. AppBarTitleTextColor - The text color of the app bar title. The default value isMaterial.Color.OnPrimary.

  4. AppBarTitleFontFamily - The font family of the app bar title. The default value isMaterial.FontFamily.H6.

  5. AppBarTitleFontSize - The font size of the app bar title. The default value is24.

  6. AppBarElevation - The size of the shadow below the app bar. The default value is4.

  7. StatusBarColor - The color of the status bar.

Usage and Behavior

This control uses the new feature of Xamarin 3.3, theTitleView property, to be able to change the appearance of the app bar title.But when theTitleView property is set on a page, the attached properties will not work.

Cards

Cards contain content and actions about a single subject.

CodeAndroidiOS
<material:MaterialCard CornerRadius="2" Elevation="1" HeightRequest="80" HorizontalOptions="FillAndExpand" />Android cardiOS card
Property

MaterialCard inherits theFrame class.

  • Elevation - The virtual distance along the z-axis. The value determines the importance of the content pesented in this view. The default value is1.

  • IsClickable - When set totrue, the card displays a ripple-effect when touched.

  • ClickCommand - The command that will run when this card was touched and the propertyIsClickable is set totrue.

  • ClickCommandParameter - The parameter to pass inClickCommand when it is executed.

Event
  • Clicked - The event that is raised when this card was touched and the propertyIsClickable is set totrue.
Usage

Cards are surfaces that display content and actions on a single topic. They should be easy to scan for relevant and actionable information. Elements, like text and images, should be placed on them in a way that clearly indicates hierarchy.

Read more about cardshere.

Buttons

Buttons allow users to take actions, and make choices, with a single tap.

There are two types of buttons you can use:MaterialButton andMaterialIconButton

CodeAndroidiOS
<material:MaterialButton BackgroundColor="#EAEAEA" HorizontalOptions="Center" Text="Elevated Button" TextColor="Black" VerticalOptions="Center" />Android buttoniOS button
Properties

MaterialButton inherits theButton class.MaterialIconButton inherits theContentView class.

Both of these controls have these common properties:

  1. ButtonType - The type of the button. The default value isElevated.

    • Elevated - This button will cast a shadow.
    • Flat - This button will have no shadow.
    • Outlined - This button will have no shadow, has a transparent background, and has a border.
    • Text - This button will only show its label. It will not have a shadow, has a transparent background, and no border.Text buttons has a smaller inner padding as compared to the other button types.
  2. BackgroundColor - The color of the button's background.Outlined and Text button types will always have a transparent background color. Flat and elevated buttons have a default background color based on the value ofMaterialColorConfiguration.Secondary.

  3. PressedBackgroundColor - The color of the button's background when it is pressed.

  4. DisabledBackgroundColor - The color of the button's background when it is disabled.

  5. Elevation - The virtual distance along the z-axis.

MaterialButton have these properties:

  1. Image - The icon to be displayed next to the button's label. The color of the icon will be based on theTextColor property value of the button.

  2. AllCaps - Whether the letters in the label of the button should be in upper case or not. By default, this is set totrue.

MaterialIconButton has this property:

  1. Image - The image of the button.

  2. TintColor - The tint color of the image.

Usage & Behavior

Buttons communicate actions that users can take. They are typically placed throughout your UI.

  • Elevated andFlat

    contained buttons

    These are high-emphasis buttons that are distinguished by their fill color and/or shadow. The actions bound to them are primary to your app.

  • Outlined

    outlined buttons

    These are medium-emphasis buttons. The actions bound to them are important, but are not the primary action in an app.

  • Text

    outlined buttons

    These buttons are typically used for less-pronounced actions, which are located in modal dialogs or in cards.

You can set theElevation property of the button using XAML or C# code. You can also set values when the button is in normal state or pressed state.

Using XAML

<!-- Button with a normal and pressed elevation of `4`--><material:MaterialButtonElevation="4"Text="Click" /><!-- Button with a normal elevation of `4` and pressed elevation of `8`--><material:MaterialButtonElevation="4, 8"Text="Click" />

Using C#

// Button with a normal and pressed elevation of `4`varbutton1=newMaterialButton(){Elevation=newMaterialElevation(4),Text="Click"};// Button with a normal and pressed elevation of `4` using implicit operatorvarbutton2=newMaterialButton(){Elevation=4,Text="Click"};// Button with a normal elevation of `4` and pressed elevation of `8`varbutton3=newMaterialButton(){Elevation=newMaterialElevation(4,8),Text="Click"};

On press, buttons display touch feedback (ripple effect).

Read more about buttonshere.

Text Fields

Text fields allow users to enter and edit text.

CodeAndroidiOS
<material:MaterialTextField Placeholder="Placeholder" HelperText="Helper Text" ErrorText="Error Text" Text="Input Text" InputType="Default" />iOS buttoniOS button
Properties

MaterialTextField inherits theContentView class.

  1. AlwaysShowUnderline - Boolean flag determines whether the underline accent of this text field should always show or not. The default value isfalse.

  2. BackgroundColor - The background color of the text field. Default hex color value is#DCDCDC.

  3. ErrorColor - The color to indicate an error in the text field. The default value is based on the color value ofMaterialColorConfiguration.Error.

  4. ErrorText - The text that will show to indicate an error in this text field. This will replaceHelperText whenHasError is set totrue.

  5. ErrorIcon - The icon that will show to indicate an error in this text field. Will show whenHasError is set totrue.

  6. FocusCommand - The command that will be executed when this text field receives or loses focus.

  7. HasError - Boolean flag that indicates whether an error has occurred or not in this text field.

  8. HelperText - The text that appears below the text field to indicate additional hints for the text field.

  9. HelperTextColor - The color of the helper text. The default hex color value is#99000000.

  10. HelperTextFontFamily - The font family of the helper text. TheErrorText will use this as its font family.

  11. LeadingIcon - The image icon that will show on the left side of this text field.

  12. LeadingIconTintColor - The color to be used to tint the icon image of this text field. The default hex color value is#99000000.

  13. InputType - The keyboard input type to be used for this text field.

  14. MaxLength - The maximum allowed number of characters in this text field.

  15. Placeholder - The placeholder text of this text field. This property must never be null or empty.

  16. PlaceholderColor - The color of the placeholder text. The default hex color value is#99000000.

  17. ReturnType - The appearance of the return button of the keyboard.

  18. ReturnCommand - The command that will run when the user returns the input.

  19. ReturnCommandParameter - The parameter to be passed inReturnCommand property when it is executed.

  20. Text - The input text of this text field.

  21. TextChangeCommand - The command that executes when there is a change in this text field's input text.

  22. TextColor - The color of the input text. The default hex color value is#D0000000.

  23. TextFontFamily - The font family of the input text. By default, it uses theMaterialFontConfiguration.Body2 font family.

  24. TintColor - The tint color of the underline accent and the placeholder of this text field when focused. The default color is set to the value ofMaterialColorConfiguration.SecondaryColor.

  25. FloatingPlaceholderEnabled - Determines whether the placeholder should float above when the text field is focused.

  26. Choices - When theInputType property is set toMaterialInputType.Choice, provides the list of choices from which the user will select one.

  27. ChoicesBindingName - The name of the property of the items in theChoices property to display.

  28. ChoiceSelectedCommand - The command that will execute when an item is selected using the input typeChoice. The parameter that will be passed to this command is the selected item.

  29. HorizontalPadding - The value that determines the left and right padding of the text field.

  30. IsSpellCheckEnabled - Boolean flag determines whether spell checking is enabled in this text field.

  31. IsTextPredictionEnabled - Boolean flag determines whether text prediction is enabled in this field.

  32. TextFontSize - The font size of the text field's input text.

  33. FloatingPlaceholderFontSize - The font size of the text field's floating placeholder.

  34. FloatingPlaceholderColor - The color of the text field's floating placeholder.

  35. IsAutocapitalizationEnabled - Boolean value that determines whether to autocapitalize the input text or not.

  36. IsMaxLengthCounterVisible - Boolean value that determines whether to show the max input length counter on not.

  37. ShouldAnimateUnderline - Boolean value that determines whether to anumate the underline indicator or not.

Events
  1. Focused - Raised when this text field receives focus.

  2. Unfocused - Raised when this text field loses focus.

  3. TextChanged - Raised when the input text of this text field has changed.

  4. ChoiceSelected - The event that will be raised when an item is selected using the input typeChoice. Gives the item that was selected.

  5. Completed - The event that will be raised when the user completes the input using the return key.

Usage and Behavior

A text field container, by default, has a fill. You can make the text field'sBackgroundColor transparent andAlwaysShowUnderline totrue.

The placeholder text should always be visible, because it is used to inform users as to what information is requested for a text field.

Helper text conveys additional guidance about the input field, such as how it will be used. It should only take up a single line, being persistently visible or visible only on focus.

When input text isn�t accepted, an error text can display instructions on how to fix it. Error messages are displayed below the input line, replacing helper text until fixed.

Read more about text fieldshere.

Selection Controls

Selection controls allow users to complete tasks that involve making choices such as selectingoptions, or switching settings on or off. Selection controls are found on screens that askusers to make decisions or declare preferences such as settings or dialogs.

Radio Buttons

Allow users to select one option from a set.

CodeAndroidiOS
<material:MaterialRadioButtonGroup x:Name="radioButtonGroup" Choices="{Binding Jobs}" />Android buttoniOS button
Properties
  1. Choices - The list of string the user will choose from.

  2. FontFamily - The font family of the text of each radio buttons. The default is the value ofMaterialFontConfiguration.Body1.

  3. FontSize - The font size of the text of each radio buttons. The default value is16.

  4. HorizontalSpacing - The spacing between the radio button and its text.

  5. SelectedColor - The color that will be used to tint this control whe selected. The default is the value ofMaterialColorConfiguration.Secondary.

  6. SelectedIndex - The index of the selected choice.

  7. SelectedIndexChanged - Raised when there is a change in the control's selected index.

  8. SelectedIndexChangedCommand - The command that wil run if there is a change in the control's selected index. The parameter is the selected index.

  9. TextColor - The color of the text of each radio button. The default value is#DE000000.

  10. UnselectedColor - The color that will be used to tint this control when unselected. The default value is#84000000.

  11. VerticalSpacing - The spacing between each radio buttons.

Usage and Behavior

Use radio buttons when the user needs to see all available options. The orientation of the radio buttons is limited to vertical position, sincethe custom view used to present the radio buttons is aListView, but the scroll bars will not show since theListView's height is based on the numberof choices. Each radio button has a fixed height of48.

Checkboxes

Checkboxes allow the user to select one or more items from a set.

CodeAndroidiOS
<material:MaterialCheckboxGroup x:Name="checkBoxGroup" Choices="{Binding Jobs}" />Android buttoniOS button
Properties
  1. Choices - The list of string the user will choose from.

  2. FontFamily - The font family of the text of each checkboxes. The default is the value ofMaterialFontConfiguration.Body1.

  3. FontSize - The font size of the text of each checkboxes. The default value is16.

  4. HorizontalSpacing - The spacing between the checkbox and its text.

  5. SelectedColor - The color that will be used to tint this control whe selected. The default is the value ofMaterialColorConfiguration.Secondary.

  6. SelectedIndices - The indices of the selected choices.

  7. SelectedIndicesChanged - Raised when there is a change in the control's selected inices.

  8. SelectedIndicesChangedCommand - The command that wil run if there is a change in the control's selected indices. The parameter is the list of selected indices.

  9. TextColor - The color of the text of each radio button. The default value is#DE000000.

  10. UnselectedColor - The color that will be used to tint this control when unselected. The default value is#84000000.

  11. VerticalSpacing - The spacing between each checkboxes.

Usage and Behavior

It has the same limitations asMaterialRadioButtonGroup.

Checkboxes can be used to turn an option on or off. If there is only one option, you can useMaterialCheckbox instead.

MaterialCheckbox has the propertyIsSelected, you can use this to determine whether the option was selected or not.

Menus

Menus display a list of choices on temporary surfaces.

CodeAndroidiOS
<material:MaterialMenuButton ButtonType="Text" CornerRadius="24" Choices="{Binding Actions}" Command="{Binding MenuCommand}" />Android buttoniOS button
Properties

MaterialMenuButton inherits theXF.Material.Forms.UI.MaterialIconButton class.

  1. Choices - The list of items from which the user will choose from. You can either assign a collection ofstring orMaterialMenuItem.

  2. MenuBackgroundColor - The background color of the menu.

  3. MenuCornerRadius - The corner radius of the menu.

  4. Command - The command that will execute when a menu item was selected. The type isCommand<MaterialMenuResult>. The result will contain the index of the selected menu and the parameter, if any.

  5. CommandParameter - The parameter to pass inCommand property.

  6. MenuTextColor - The text color of the menu items.

  7. MenuTextFontFamily - The text font family of the menu items.

Event
  1. MenuSelected - Raised when a menu item was selected.
Usage and Behavior

Menus are positioned relative to both the element that generates them and the edges of the screen. They can appear in front of, beside, above, or below the element that generates them.

Menus can be dismissed by tapping outside, when an item was selected, or when the back button was pressed in Android.

Be sure to always match the width and height of the child view to the width and height of the menu.

Menu is by default a button. In the menu sample shown above the 3 dots is an added image. This is one of the possibilities how the menu can look like.

Slider

Sliders allow users to make selections from a range of values.

<mat:MaterialSliderValue="{Binding CurrentValue}"MinValue="0"MaxValue="100" />
Properties

MaterialSlider inherits theContentView class.

  1. Value - The current value selected.

  2. MinValue - The minimum value allowed to select.

  3. MaxValue - The maximum value allowed to select.

  4. ValueChangedCommand - The command that will execute when the current value has changed.

  5. TrackColor - The track color of the slider.

  6. ThumbColor - The thumb color of the slider.

Event
  1. ValueChanged - The event that is raised when the current value has changed.

Switch

Switches allow the user to toggle between two states.

<mat:MaterialSwitchIsActivated="{Binding IsTracking}" />
Properties

MaterialSwitch inherits theContentView class.

  1. ActiveTrackColor - The track color of the switch when it is in active state.

  2. ActiveThumbColor - The thumb color of the switch when it is in active state.

  3. InactiveTrackColor - The track color of the switch when it is in inactive state.

  4. InactiveThumbColor - The thumb color of the switch when it is in inactive state.

  5. IsActivated - Boolean flag whether the switch was activated or not.

Event
  1. Activated - The event that is raised when the switch was activated or not.

Typography Label

A view that displays a text. Allows customizations to conform with the typography guidelines.

Properties

MaterialLabel inherits theLabel class.

  1. TypeScale - In material design, these are categories on how the text are displayed. Each type scale has its own font family, font weight, font size, and letter spacing. For more info about type scale, readhere.

  2. LineHeight - The factor to multiply that will identify the distance between the base of a line of text to another. The default value is1.4.

Chips

Chips are compact elements that represent an input, attribute, or action.

CodeAndroidiOS
<material:MaterialChip BackgroundColor="#F2F2F2" Image="im_google" Text="Google" TextColor="#DE000000" />Android buttoniOS button
Properties

MaterialChip inherits theContentView class.

  1. Text - The chip's label to be displayed.

  2. TextColor - The color of the chip's label.

  3. FontFamily - The font family of the chip's label.

  4. BackgroundColor - The color of the chip's background.

  5. Image - The chip's image to be displayed.

  6. ActionImage - The chip's action image to be displayed.

  7. ActionImageTappedCommand - The bindable command that executes when theActionImage of the chip is tapped.

Event
  1. ActionImageTapped - The event that is called when theActionImage of the chip is tapped.
Usage and Behavior

Chips allow users to enter information, make selections, filter content, or trigger actions.

Read more about chipshere.

Circular Progress Indicator

An indeterminate progress indicator that express an unspecified wait time of a process.

Code
<material:MaterialCircularLoadingViewWidthRequest="56"HeightRequest="56"TintColor="#6200EE" />
Properties

MaterialCircularLoadingView inherits theLottie.Forms.AnimationView class.

  1. TintColor - The color of the circular progress indicator.
Usage & Behavior

Circular progress indicators display progress by animating an indicator along an invisible circular track in a clockwise direction. They can be applied directly to a surface, such as a button or card.

Loading Dialog uses this to indicate a process running.

Read more about circular progress indicatorhere.

Tintable Image Icon

A tintable image view.

Code
<material:MaterialIconWidthRequest="56"HeightRequest="56"Source="ic_save"TintColor="#6200EE" />
Properties

MaterialIcon inherits theImage class.

  1. TintColor - The tint color of the image.

Material Dialogs

Under theXF.Material.Forms.UI.Dialogs namespace, you can display modal views to notify users by usingMaterialDialog.Instance.

Handling the Back Button on Android

In order for the back button to work on Android for dismissing dialogs, override theOnBackPressed method in yourMainActivity class and add this:

publicoverridevoidOnBackPressed(){XF.Material.Droid.Material.HandleBackButton(base.OnBackPressed);//No need to call  Rg.Plugins.Popup.Popup.SendBackPressed();}

Important
If you are usingRg.Plugins.Popup, usingXF.Material.Droid.Material.HandleBackButton(base.OnBackPressed) will callPopup.SendBackPressed whenthere is a modal page that is not a shown usingMaterialDialog.Instance.

Alert Dialog

Alert dialogs interrupt users with urgent information, details, or actions.

AndroidiOS
Android buttoniOS button
Code

You can show an alert dialog using any of the following overload methods ofMaterialDialog.Instance.AlertAsync() orMaterialDialog.Instance.ConfirmAsync().

There are two common parameters in this method:

  1. message - The message of the alert dialog.

  2. title - The title of the alert dialog.

  • Shows an alert dialog for acknowledgement. It only has a single, dismissive action used for acknowledgement.

    awaitMaterialDialog.Instance.AlertAsync(message:"This is an alert dialog.");awaitMaterialDialog.Instance.AlertAsync(message:"This is an alert dialog",title:"Alert Dialog");awaitMaterialDialog.Instance.AlertAsync(message:"This is an alert dialog",title:"Alert Dialog",acknowledgementText:"Got It");
    • acknowledgementText - The text of the alert dialog's acknowledgement button. The default string value isOk.
  • Showing an alert dialog for confirmation of action. Returns true when the confirm button was clicked, false if the dismiss button was clicked or if the alert dialog was dismissed.

    awaitMaterialDialog.Instance.ConfirmAsync(message:"Do you want to sign in?",confirmingText:"Sign In");awaitMaterialDialog.Instance.ConfirmAsync(message:"Do you want to sign in?",confirmingText:"Sign In",dismissiveText:"No");awaitMaterialDialog.Instance.ConfirmAsync(message:"Discard draft?",title:"Confirm",confirmingText:"Yes",dismissiveText:"No");
    • confirmingText - The text of the alert dialog's confirmation button.

    • dismissiveText - The text of the alert dialog's dismissive button. The default string value isCancel.

Usage & Behavior

An alert dialog is displayed by pushing a modal window. This will appear in front of the content of the app to provide critical information or ask for a decision.

Alert dialogs are interruptive. This means that it disables all app functionality when they appear, and remain on screen until confirmed, dismissed or a required action has been taken.

Alert dialogs may be dismissed by tapping outside of the dialog, tapping the dismissive button (e.g. "Cancel" button), or by tapping the system back button (for Android).

Read more about alert dialogshere.

Custom Alert Dialog Content

You can show a custom dialog content by using theMaterialDialog.Instance.ShowCustomContentAsync().

Android button

varchoices=newstring[]{"Biology","Psychology","Phsyics","Chemistry"};varview=newMaterialRadioButtonGroup(){Choices=choices};bool?wasConfirmed=awaitMaterialDialog.Instance.ShowCustomContentAsync(view,"What field of science is considered as the study of life?","Question 1");

This method returns a nullablebool. Returnstrue when the user dismisses the dialog using the confirm button,false when using the dismiss button, andnull when using the back button or when the background was clicked.

You can pass parameters as like what you would do in when usingMaterialDialog.Instance.ConfirmAsync(). The onlydifference is that it takes aView as a parameter and this will be shown inside the dialog.

You can remove the negative button by passingnull to thedismissiveText parameter.

Simple Dialog

Simple dialogs can display items that are immediately actionable when selected. They don’t have text buttons.

AndroidiOS
Android buttoniOS button
Code

You can show a simple dialog by using any of the overload methods ofMaterialDialog.Instance.SelectActionAsync().

//Create actionsvaractions=newstring[]{"Open in new tab","Open in new window","Copy link address","Download link"};//Show simple dialogvarresult=awaitMaterialDialog.Instance.SelectActionAsync(actions:actions);//Show simple dialog with titlevarresult=awaitMaterialDialog.Instance.SelectActionAsync(title:"Select an action",actions:actions);
Usage & Behavior

Simple dialogs are dismissed by tapping an action, or by tapping outside the dialog.

Read more about alert dialogshere.

Confirmation Dialog

Confirmation dialogs give users the ability to provide final confirmation of a choice before committing to it,so they have a chance to change their minds if necessary.

AndroidiOS
Android buttoniOS button
Code

You can show two types of confirmation dialog: Choose one of listed choices usingMaterialDialog.Instance.SelectChoiceAsync(), and choose one or more of listed choices usingMaterialDialog.Instance.SelectChoicesAsync().

//Create choicesvarjobs=newstring[]{"Mobile Developer (Xamarin)","Mobile Developer (Native)","Web Developer (.NET)","Web Developer (Laravel)","Quality Assurance Engineer","Business Analyst","Recruitment Officer","Project Manager","Scrum Master"};//Show confirmation dialog for choosing one.varresult=awaitMaterialDialog.Instance.SelectChoiceAsync(title:"Select a job",choices:jobs);//Show confirmation dialog for choosing one or more.varresult=awaitMaterialDialog.Instance.SelectChoicesAsync(title:"Select a job",choices:jobs);

You can also define pre-selected choice/s by supplying the parametersselectedIndex andselectedIndices forMaterialDialog.Instance.SelectChoiceAsync() andMaterialDialog.Instance.SelectChoicesAsync(), respectively.

...//Show confirmation dialog for choosing one, with pre-selected choice.var result=awaitMaterialDialog.Instance.SelectChoiceAsync(title:"Select a job",selectedIndex:1,choices:jobs);//Show confirmation dialog for choosing one or more, with pre-selected choices.varresult=awaitMaterialDialog.Instance.SelectChoicesAsync(title:"Select a job",selectedIndices:newint[]{1,0},choices:jobs);
Usage and Behavior

Confirmation dialogs provide both confirmation and cancel buttons. After a confirmation button is tapped, a selection is confirmed.If the cancel button is tapped, or the area outside the dialog, the action is cancelled.

The confirmation button will only be enabled when an item is selected.

Input Dialog

A type of confirmation dialog that allow users to input text and confirm it.

AndroidiOS
Android buttoniOS button
Code

You can show an input dialog by calling any of the overload methods ofMaterialDialog.Instance.InputAsync().

varinput=awaitMaterialDialog.Instance.InputAsync();
Usage and Behavior

Just like confirmation dialogs, input dialogs also provide confirmation and cancel buttons. It will return the string value of the input field if the confirm button was clicked. If the cancel button is tapped, or the area outside the dialog, the action is cancelled.

Loading Dialog

A modal dialog that is displayed to inform users about a process that is running for an unspecified time.

AndroidiOS
Android buttoniOS button
Code

You can show a loading dialog using either of two ways:

  • Show in ausing block. The loading dialog will automatically dispappear when the task/s are done.
using(awaitMaterialDialog.Instance.LoadingDialogAsync(message:"Something is running")){awaitTask.Delay(5000)// Represents a task that is running.}
  • Show by calling the method and assign the return value to a variable, then call theDispose method of the variable to hide the loading dialog after all task/s are done.
varloadingDialog=awaitMaterialDialog.Instance.LoadingDialogAsync(message:"Something is running");awaitTask.Delay(5000)// Represents a task that is running.await loadingDialog.DismissAsync();
  • Change the dialog's text.
using(vardialog=awaitMaterialDialog.Instance.LoadingDialogAsync(message:"Something is running")){awaitTask.Delay(5000)// Represents a task that is running.    dialog.Text="Something else is running now!";awaitTask.Delay(5000)// Represents a task that is running.}
Usage & Behavior

Show a loading dialog to inform users of a running process in your app.

A loading dialog can never be dismissed by user interaction, even by using Android's back button.

Snackbar

Snackbars provide brief messages about app processes at the bottom of the screen.

AndroidiOS
Android buttoniOS button
Code

You can show a snackbar by using either of the two overload methods ofMaterialDialog.Instance.SnackbarAsync().

Both methods have this default parametermessage, which is the message that will display on the snackbar.

  • Shows a snackbar with no action.

    awaitMaterialDialog.Instance.SnackbarAsync(message:"This is a snackbar.",msDuration:MaterialSnackbar.DurationLong);
    • msDuration - The duration, in milliseconds, before the snackbar will disappear. There are pre-defined constants which you can use in theMaterialSnackbar class.
      • MaterialSnackbar.DurationShort - Snackbar will show for 1500 milliseconds.

      • MaterialSnackbar.DurationLong - Snackbar will show for 2750 milliseconds. The default value ofmsDuration.

      • MaterialSnackbar.DurationIndefinite - Snackbar will show indefinitely.

  • Shows a snackbar with an action. Returns true if the snackbar's action button was clicked, or false if the snackbar was automatically dismissed.

    awaitMaterialDialog.Instance.SnackbarAsync(message:"This is a snackbar.",actionButtonText:"Got It",msDuration:3000);
    • actionButtonText - The text that will appear on the snackbar's button.

You can also use a snackbar to indicate a task/s running without interrupting the user. You can use theMaterialDialog.Instance.LoadingSnackbarAsync() method.

There are two ways to display a loading snackbar.

  • Show in ausing block. The loading dialog will automatically dispappear when the task/s are done.
using(awaitMaterialDialog.Instance.LoadingSnackbarAsync(message:"Something is running")){awaitTask.Delay(5000)// Represents a task that is running.}
  • Show by calling the method and assign the return value to a variable, then call theDispose method of the variable to hide the snackbar after all task/s are done.
varsnackbar=awaitMaterialDialog.Instance.LoadingSnackbarAsync(message:"Something is running");awaitTask.Delay(5000)// Represents a task that is running.await snackbar.DismissAsync();
  • Change the snackbar's text.
using(varsnackbar=awaitMaterialDialog.Instance.LoadingSnackbarAsync(message:"Something is running")){awaitTask.Delay(5000)// Represents a task that is running.    snackbar.Text="Something else is running now!";awaitTask.Delay(5000)// Represents a task that is running.}
Usage & Behavior

Snackbars can be used to inform users of a process that an app has performed, will perform, or is performing. They can appear temporarily towards the bottom of the screen. Only one snackbar may be displayed at a time.

A snackbar can contain a single action. When setting the duration of how long before it disappears automatically, the action shouldn't be "Dismiss" or "Cancel".

Read more about snackbarshere.

Styling Dialogs

You can customize modal dialogs that are shown usingMaterialDialog.Instance.

BaseMaterialDialogConfiguraion, which the classesMaterialAlertDialogConfiguration,MaterialLoadingDialogConfiguration, andMaterialSnackbarConfiguration inherits, has these properties:

  1. BackgroundColor - The background color of the dialog. The default value isColor.White.

  2. CornerRadius - The roundness of the dialog's corners. The default value is2. ForMaterialSnackbarConfiguration, the value is4.

  3. MessageFontFamily - The font family of the dialog's message. The default value is set to the value ofMaterialFontConfiguration.Body1. ForMaterialSnackbarConfiguration, the default value is set to the value ofMaterialFontConfiguration.Body2.

  4. MessageTextColor - The color of the dialog's message. The default value is#99000000. ForMaterialSnackbarConfiguration, the default value is#DEFFFFFF.

  5. ScrimColor - The color that will appear at the back of this dialog. The default value is#51000000. ForMaterialSnackbarConfiguration, the value isColor.Transparent.

  6. TintColor - The color to tint views such as buttons and images. The default value is set to the value ofMaterialColorConfiguration.Secondary. ForMaterialSnackbarConfiguration, the default value isColor.Yellow.

Styling Alert Dialogs

MaterialAlertDialogConfiguration class provides properties to be used for customizing an alert dialog. You can pass an instance of this class to any overload methods ofMaterialDialog.Instance.AlertAsync().

The properties ofMaterialAlertDialogConfiguration class are:

  1. TitleTextColor - The color of the alert dialog's title. The default color hex value is#DE000000;

  2. TitleFontFamily - The font family of the alert dialog's title. The default value is set to the value ofMaterialFontConfiguration.H6.

  3. ButtonFontFamily - The font family of the alert dialog's button/s. The default value is set to the value ofMaterialFontConfiguration.Button.

  4. ButtonAllCaps - The boolean value whether the text of the alert dialog's button/s should all be capitalized or not. The default value istrue.

varalertDialogConfiguration=newMaterialAlertDialogConfiguration{BackgroundColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.PRIMARY),TitleTextColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ONPRIMARY),TitleFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.Exo2Bold"),MessageTextColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ONPRIMARY).MultiplyAlpha(0.8),MessageFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansRegular"),TintColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ONPRIMARY),ButtonFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansSemiBold"),CornerRadius=8,ScrimColor=Color.FromHex("#232F34").MultiplyAlpha(0.32),ButtonAllCaps=false};awaitMaterialDialog.Instance.AlertAsync(message:"This is an alert dialog",title:"Alert Dialog",acknowledgementText:"Got It",configuration:alertDialogConfiguration);


You can also pass the same configuration when you want to style alert dialogs with custom content. But you wouldhave to update also the style of the custom view separately.


Styling Simple Dialogs

MaterialSimpleDialogConfiguration class provides properties to be used for customizing a simple dialog. You can pass an instance of this class to any overload methods ofMaterialDialog.Instance.SelectActionAsync().

varsimpleDialogConfiguration=newMaterialSimpleDialogConfiguration{BackgroundColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.PRIMARY),TitleTextColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ON_PRIMARY),TitleFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansSemiBold"),TextColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ON_PRIMARY).MultiplyAlpha(0.8),TextFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansRegular"),CornerRadius=8,ScrimColor=Color.FromHex("#232F34").MultiplyAlpha(0.32)};varresult=awaitMaterialDialog.Instance.SelectActionAsync(title:"Select an action",actions:newstring[]{"Open in new tab","Open in new window","Copy link address","Download link"},configuration:simpleDialogConfiguration);

Styling Confirmation Dialogs

MaterialConfirmationDialogConfiguration class provides properties to be used for customizing a confirmation dialog. You can pass an instance of this class to any overload methods ofMaterialDialog.Instance.SelectChoiceAsync() orMaterial.Instance.SelectChoicesAsync().

varconfirmationDialogConfiguration=newMaterialConfirmationDialogConfiguration{BackgroundColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.PRIMARY).AddLuminosity(-0.1),TitleTextColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ON_PRIMARY),TitleFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansSemiBold"),TextColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ON_PRIMARY).MultiplyAlpha(0.8),TextFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansRegular"),CornerRadius=8,ButtonAllCaps=false,ButtonFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansSemiBold"),ControlSelectedColor=Color.White,ControlUnselectedColor=Color.White.MultiplyAlpha(0.66),TintColor=Color.White,ScrimColor=Color.FromHex("#232F34").MultiplyAlpha(0.32)};varresult=awaitMaterialDialog.Instance.SelectChoiceAsync(title:"Select a  job",choices:/*choices list*/,configuration:confirmationDialogConfiguration);

Styling Input Dialogs

MaterialInputDialogConfiguration class provides properties to be used for customizing an input dialog.You can pass an instance of this class to any overload methods ofMaterialDialog.Instance.InputAsync().

The input type of the input field can be set by using this configuration.

varconfig=newMaterialInputDialogConfiguration(){InputType=MaterialTextFieldInputType.Password,CornerRadius=8,BackgroundColor=Color.FromHex("#2c3e50"),InputTextColor=Color.White,InputPlaceholderColor=Color.White.MultiplyAlpha(0.6),TintColor=Color.White,TitleTextColor=Color.White,MessageTextColor=Color.FromHex("#DEFFFFFF")};varinput=awaitMaterialDialog.Instance.InputAsync(title:"Deactivate account",message:"To continue, please enter your current password",inputPlaceholder:"Password",confirmingText:"Deactivate",configuration:config);

Styling Loading Dialogs

MaterialLoadingDialogConfiguration class provides properties to be used for customizing a loading dialog. You can pass an instance of this class to any overload methods ofMaterialDialog.Instance.LoadingDialogAsync().

varloadingDialogConfiguration=newMaterialLoadingDialogConfiguration(){BackgroundColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.PRIMARY),MessageTextColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ONPRIMARY).MultiplyAlpha(0.8),MessageFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansRegular"),TintColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ONPRIMARY),CornerRadius=8,ScrimColor=Color.FromHex("#232F34").MultiplyAlpha(0.32)};awaitMaterialDialog.Instance.LoadingDialogAsync(message:"Something is running...",configuration:loadingConfiguration);

Styling Snackbars

MaterialSnackbarConfiguration class provides properties to be used for customizing a snackbar. You can pass an instance of this class to any overload methods ofMaterialDialog.Instance.SnackbarAsync() orMaterialDialog.Instance.LoadingSnackbarAsync().

varsnackbarConfiguration=newMaterialSnackbarConfiguration(){BackgroundColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.PRIMARY),MessageFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansRegular"),ButtonAllCaps=true,ButtonFontFamily=XF.Material.Forms.Material.GetResource<OnPlatform<string>>("FontFamily.OpenSansSemiBold"),TintColor=Color.White,MessageTextColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.ONPRIMARY).MultiplyAlpha(0.8)}await MaterialDialog.Instance.SnackbarAsync(message:"This is a snackbar."                                            actionButtonText:  "Got It",configuration:snackbarConfiguration);

Setting a global style for each type of dialogs

You can set the global styles of each dialog by using theMaterialDialog.Instance.SetGlobalStyles() method.

You can still override these styles be passing the configuration object when showing an alert dialog, loading dialog, simple dialog, confirmation dialog, and snackbar.

Material Resources

You can create Material-based resources which will be used by your app. This library strictly follows Google's Material Design, following principles of good design while maintaining a common UI across platforms.

TheMaterialConfiguration class allow you to define your theme and combine it along with the built in resource dictionary to your app.

Color

You can fully express your branding with the use of the baseline Material color theme, while creating a uniform, cross-platform design.

Use theColor Tool to create your palette. This tool provides a preview of what your UI will look like while keeping accessibility.

You can define your color theme with theMaterialColorConfiguration class. The properties of the class are:

  1. Primary - Displayed most frequently across your app.MaterialNavigationPage uses this color as its defaultBarBackgroundColor.

  2. PrimaryVariant - A tonal variation of thePrimary color. Used for coloring the status bar.

  3. Secondary - Accents select parts of your UI. If not defined, it will use thePrimary color.MaterialButton (including the buttons inAlert Dialogs),MaterialTextField andMaterialCircularLoadingView uses this color value as their default accent color.

  4. SecondaryVariant - A tonal variation of theSecondary color.

  5. Background - The underlying color of an app's content. The root page and pages pushed by theMaterialNavigationPage control will have theirBackgroundColor property set to this value by default, unless there is already a value defined in the page.

  6. Error - The color used to indicate error status.

  7. Surface - The color of surfaces such as cards.MaterialCard uses this color value as itsBackgroundColor.

  8. OnPrimary - A color that passes accessibility guidelines for text/iconography when drawn on top of thePrimary color.MaterialNavigationPage uses this color as itsBarTextColor by default.

  9. OnSecondary - A color that passes accessibility guidelines for text/iconography when drawn on top of theSecondary color.MaterialButton typesElevated andFlat use this color value as their defaultTextColor.

  10. OnBackground - A color that passes accessibility guidelines for text/iconography when drawn on top of theBackground color.

  11. OnError - A color that passes accessibility guidelines for text/iconography when drawn on top of theError color.

  12. OnSurface - A color that passes accessibility guidelines for text/iconography when drawn on top of theSurface color.

If you did not set theColorConfiguration property of theMaterialConfiguration class inhere, it will use a default color theme.

Typography

As statedhere, you can use typography to present your design and content as clearly and efficiently as possible.

Type Scale

The Material Design type scale includes a range of contrasting styles that support the needs of your product and its content. These are resusable categories of text, each with an intended application and meaning.

This library offers the same type scales, each can be applied and reused in your app.


TypeScaleFont SizeFont AttributeLetter Spacing
MaterialTypeScale.H196Regular-1.5
MaterialTypeScale.H260Regular-0.5
MaterialTypeScale.H348Regular0
MaterialTypeScale.H434Regular0.25
MaterialTypeScale.H524Regular0
MaterialTypeScale.H620Bold0.15
MaterialTypeScale.Subtitle116Regular0.15
MaterialTypeScale.Subtitle214Bold0.1
MaterialTypeScale.Body116Regular0.5
MaterialTypeScale.Body214Regular0.25
MaterialTypeScale.Button14Bold0.75
MaterialTypeScale.Caption12Regular0.4
MaterialTypeScale.Overline10Regular1.5
  • Headlines - The largest text on the screen, and used for short, important text or numerals.

  • Subtitles - Smaller than headlines. Typically used for medium-emphasis text that is shorter in length.

  • Body - Used for long-form writing as it works well for small text sizes.

  • Caption and Overline - Smallest font sizes. Used sparingly to annotate imagery or to introduce a headline.

  • Button - Used for different types of buttons.MaterialButton automatically applies this style.

Read more about applying the type scalehere.

Applying a Type Scale

You can apply a type scale to a text usingMaterialLabel.

Setting a Font Family to a Type Scale

TheMaterialFontConfiguration class allows you to set a specific font to a type scale.

Adding the Material Resources

The code below shows a complete example on how to include theMaterialColorConfiguration andMaterialFontConfiguration.

<Applicationx:Class="XF.MaterialSample.App"xmlns="http://xamarin.com/schemas/2014/forms"xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"xmlns:mtrl="clr-namespace:XF.Material.Forms.Resources;assembly=XF.Material"xmlns:mtrltypo="clr-namespace:XF.Material.Forms.Resources.Typography;assembly=XF.Material">    <Application.Resources>        <OnPlatformx:Key="FontFamily.RobotoRegular"x:TypeArguments="x:String"Android="Fonts/Roboto-Regular.ttf#Roboto-Regular"iOS="Roboto-Regular" />        <OnPlatformx:Key="FontFamily.RobotoMedium"x:TypeArguments="x:String"Android="Fonts/Roboto-Medium.ttf#Roboto-Medium"iOS="Roboto-Medium" />        <mtrltypo:MaterialFontConfigurationx:Key="Material.Font"Body1="{StaticResource FontFamily.RobotoRegular}"Body2="{StaticResource FontFamily.RobotoRegular}"Button="{StaticResource FontFamily.RobotoMedium}"Caption="{StaticResource FontFamily.RobotoRegular}"H1="{StaticResource FontFamily.RobotoRegular}"H2="{StaticResource FontFamily.RobotoRegular}"H3="{StaticResource FontFamily.RobotoRegular}"H4="{StaticResource FontFamily.RobotoRegular}"H5="{StaticResource FontFamily.RobotoRegular}"H6="{StaticResource FontFamily.RobotoMedium}"Overline="{StaticResource FontFamily.RobotoRegular}"Subtitle1="{StaticResource FontFamily.RobotoRegular}"Subtitle2="{StaticResource FontFamily.RobotoMedium}" />        <mtrl:MaterialColorConfigurationx:Key="Material.Color"Background="#EAEAEA"Error="#B00020"OnBackground="#000000"OnError="#FFFFFF"OnPrimary="#FFFFFF"OnSecondary="#FFFFFF"OnSurface="#000000"Primary="#011A27"PrimaryVariant="#000000"Secondary="#063852"SecondaryVariant="#001229"Surface="#FFFFFF" />        <mtrl:MaterialConfigurationx:Key="Material.Configuration"ColorConfiguration="{StaticResource Material.Color}"FontConfiguration="{StaticResource Material.Font}" />    </Application.Resources></Application>

Then in yourApp.xaml.cs, pass the resource key of theMaterialConfiguration object.

MaterialFontConfiguration's andMaterialColorConfiguration's properties are optional, they always have a default value. ForMaterialFontConfiguration the default font is the system font.

// Xamarin.FormspublicApp(){InitializeComponent();XF.Material.Forms.Material.Init(this,"Material.Configuration");}

You can also instantiate theMaterialConfiguration object via C# code.

// Xamarin.FormspublicApp(){InitializeComponent();XF.Material.Forms.Material.Init(this,newMaterialConfiguration{ColorConfiguration=newMaterialColorConfiguration{// Set properties},FontConfiguration=newMaterialFontConfiguration{// Set properties}});}

Retrieving a Material Resource

The static propertiesColorConfiguration andFontConfiguration ofMaterial class allows you to retrieve the resource values that you have set.

You can also useXF.Material.Forms.Material.GetResource<T>(string key) method that allows you to get a resource value of the specified type.

The staticMaterialConstants class provides a list of constant Material resource keys.

//Get color resource, use eitherColorprimaryColor=XF.Material.Forms.Material.GetResource<Color>(MaterialConstants.Color.PRIMARY);ColorprimaryColor=XF.Material.Forms.Material.Color.Primary;//Get font family resource, use eitherstringbody1Font=XF.Material.Forms.Material.GetResource<string>(MaterialConstants.FontFamily.BODY1);stringbody1Font=XF.Material.Forms.Material.FontFamily.Body1;

Changing the Status Bar Color

You can change the color of the status bar by using theMaterial.PlatformConfiguration.ChangeStatusBarColor(Color color) method.

The status bar color is automatically changed depending on the value ofMaterialColorConfiguration.PrimaryVariant.

Android Compatibility Issues

It is recommended to use this library for applications targeting Android 5.0 (Lollipop) or higher for better rendering.

If targeted below Android 5.0, the following issues can be seen:

  • Material shadows, like that ofMaterialCard andMaterialButton, will not show.
  • On Android 4.2 (Jellybean),MaterialButton is larger. Explanation is provided in thisissue.
  • Letter spacing of typescale effects won't work for devices running below Android 5.0 (Lollipop). The API for setting the letter spacing was added in Android 5.0.

Thanks and Appreciation

Special thanks to the following libraries I used for this project:

About

A Xamarin Forms library for implementing Material Design

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

  •  

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp