Skip to end of metadata
Go to start of metadata

Since the introduction of Fragments in modern Android SDKs, the process of creating view content shifted to Fragment rather than Activity. The reason behind this is that by creating a Fragment, developers can easily re-use it in different view containers when needed. One such example is when developing an app that supports multiple screens in a device. Following this guideline, Crosslight Android Material streamlines the process of creating the view content to Fragment only.  

Material Fragment is the base class of all fragment variants. It provides comprehensive API that allows you to quickly create a view that complies to Material design guidelines. Tasks such as creating and configuring toolbar, enabling parallax image, adding bar items, adding floating action button, can be done easily through various APIs available in Fragment class.

This document covers how to customize your Android Material Fragment, but does not explain how to prepare the data and perform data binding using MVVM design pattern. To learn more about MVVM see Understanding Data Binding and MVVM Design Pattern.

Creating View Using Material Fragment

To create a view using Material Fragment, you can simply create a class that inherits from Intersoft.Crosslight.Android.v7.Fragment and override the ContentLayoutId as follows.

Note that several base classes such as Fragment<TViewModel> are available in both Intersoft.Crosslight.Android.v7 and Intersoft.Crosslight.Android. To use Material Fragment ensure that you have used the correct namespace (Intersoft.Crosslight.Android.v7).

The ContentLayoutId refers to resource layout for your content view. In this resource layout, you only need to create the content of your view. You do not need to provide toolbar, coordinator layout, floating action button, since these elements are created automatically, and can be customized through various APIs available in Material Fragment.

The default structure of Material Fragment are as follows.

  • FrameLayout (Root)
    • LinearLayout (MainContainer)
      • CoordinatorLayout
        • AppBarLayout
          • CollapsingToolbarLayout (if used)
            • Toolbar
        • View Content
        • Floating Action Buttons
    • FrameLayout (Overlay)

Your ContentLayoutId will be inflated and registered under CoordinatorLayout in the view content section.

All auto-generated elements can be configured through specific methods as follows.

Alternatively, you can also uses OnViewCreated overload to initialize any of these layouts including custom elements inside your view content.

Defining Toolbar

Toolbar describes the content and possible actions of your view. It can contain icon, title, bar items, back button and also other contents such as parallax image. Creating and customizing all of these elements for each view can be quite tedious. Crosslight Android Material attempts to streamline the implementation by providing various APIs that can be used to define and customize your toolbar easily.

Defining Back Button Visibility

When navigating to another screen, Material Fragment will automatically hide and show the back button depending on the state of the navigation. For example, when you perform push navigation, it will automatically show the back button on the new Fragment being shown. On the contrary, when you perform a drawer navigation, the Fragment won't show the back button.

If you want to override this behavior, you can set the ToolbarSettings.BackButtonVisibility as follows.

Defining Toolbar Icon

Specifying toolbar icon is quite straightforward, you only need to set the Fragment.IconId property as follows.

Defining Toolbar Title

There are several ways to specify the toolbar title. The most ideal way to specify toolbar title is from Title property in the ViewModel, so that it can be streamlined to other platforms as well. 

The following code shows you how to define the title in the ViewModel.

However, should you need to specify the title specific for android platform you can also set the title to Fragment.Title property as follows.

Defining Bar Items

Bar items (previously known as menu items) represent the actions applicable to your view. In Crosslight Android Classic, you need to specify the bar items through a separate AXML and specify the MenuLayoutId such as follows.

save_menu

Then in the Fragment:

In Crosslight Android Material, this approach is still supported. However, it's more convenient and recommended to use the new API to specify the bar items as follows.

As the result, you don't have to deal with any AXML files for adding bar items to Toolbar. There are several configurable properties such as Title, IconId, ShowAsAction, Name and also CommandItemType. The first three properties are pretty straightforward: Title defines the text of the bar item, Icon defines the icon used by the bar item, ShowAsAction defines the appearance behavior of the bar Item. The Name property is used to perform command binding, its act as button identifier, similar with specifying control id using xml. 

The CommandItemType property is a secondary property but quite useful. It provides predefined icons, title and built-in behavior for common actions found in mobile apps. The following are the list of available CommandItemType.

CommandItemTypeIconTitleBuilt-in Behavior
ActionAction 
AddAdd 
BookmarksBookmarks 
CameraCamera 
CancelCancel 
ComposeCompose 
DoneDone 
EditEdit 
FastForwardFast Forward 
Favorite Provides built-in capability to perform toggle / un-toggle favorite.
OrganizeOrganize 
PausePause 
PlayPlay 
RedoRedo 
RefreshRefresh 
ReplyReply 
RewindRewind 
SaveSave 
Search Provides built-in capability to change the search icon into search view, where user can input search text. Use in conjunction with SearchActivity or SearchableRecyclerViewFragment.
StopStop 
TrashTrash 
UndoUndo 

Using Collapsing Toolbar

CollapsingToolbar is a toolbar with larger content that can be expanded or collapsed when user scroll the content of your view. This toolbar is useful when you need to highlight certain attribute of your content such as image and header. The following code shows how to enable collapsing toolbar.

Notice that you can use CollapsingToolbarSettings.ParallaxImageId for static image, if the image is data driven you can set it through BindingProvider as follows.

You need to use the predetermined id : "ParallaxImage", for the binding provider. To bind the parallax image to dynamic source such as byte or uri.

Using Custom Header in Collapsing Toolbar

By default the header for collapsing toolbar is taken from Toolbar's title explained above. Since the content of collapsing toolbar usually rich in content, there are cases where you might need more customized header. To accommodate this, you can use CollapsingToolbarSettings.HeaderLayoutId to specify custom header content for your collapsing toolbar. The custom header will fade out when the collapsing toolbar is transforming to toolbar.

The following code shows you how to use custom header layout in your collapsing toolbar.

Here's one example of a custom header layout.

custom_header_layout

Customizing Toolbar Scrolling Behavior

When you have a content that requires scrolling, the viewing experience can be enhanced by implementing scrolling behavior to the toolbar. One of the common practices is to hide the toolbar when scrolling the content, to give larger viewport for viewing the content. To enable this scrolling behavior, you can set the ToolbarSettings.ScrollFlags for simple toolbar or CollapsingToolbarSettings.ScrollFlags for collapsing toolbar.

Note that to enable scrolling behavior your content must be placed inside a NestedScrollView (android.support.v4.widget.NestedScrollView).
For a simple Toolbar, you can use the following code to hide the toolbar when scrolling down and show the toolbar when scroll up immediately.

However, you can use ScrollFlagEnterAlwaysCollapsed if you prefer to only to show the toolbar when the content is already scrolled back to the top.

For CollapsingToolbar, when enabling the ScrollFlags, scrolling down normally will cause the entire content to move (collapsing).

You can use ScrollFlagEnterAlways similar to simple toolbar to achieve the same result. This will allow you to show the toolbar immediately when the content is scrolled up.

If you prefer the toolbar to be always visible when collapsed, you can use ScrollFlagExitUntilCollapsed as follows.

Another nice configuration for collapsing toolbar is the snap behavior. You can enable the snap behavior by using the following code.

The snap behavior will return to the original state when the scrolling ends and the view has been reduced to less than 50% of its original height and vice versa.

Using Sticky Header

Using CollapsingToolbar with scrolling behavior will make your custom header template invisible when the content is scrolled down. If you want the custom header to be sticky, you need to create the header outside the toolbar. The easiest way to enable this is by creating a custom layout outside the NestedScrollView as follows.

Defining Floating Action Button

Another Material UI element that is becoming a standard in Material apps is the Floating Action Button. Floating Action Button defines the main action that you want your user to perform in the current view. To add a Floating Action Button in your Fragment, you can use FloatingActionButton component model as follows.

Similar to bar items, you can use CommandItemType to specify the common command type typically found in mobile apps such as Add, Edit, and more. If you want to use custom icon, you can set the icon by specifying the IconId. Note that the built-in behavior for CommandItemType.Search is not applicable in Floating Action Button, although custom command will continue to work as expected.

Customizing Button Position

Floating Action Button is usually positioned at bottom right of your screen. However, you can change the position using Position property. The supported position values are: BottomRight, BottomLeft, BottomCenter, TopRight, TopLeft, and TopCenter.

The following code shows you how to position your Floating Action Button to bottom center.

Here's the result of the above code.

Customizing Layout Direction

You can add more than one Floating Action Buttons in certain position. The newly added button will be positioned relative to Direction property. You can choose either Up, Left, Right and Down direction. For example, when you position the Floating Action Button at the bottom center, when Up direction is used, the next button will be positioned on top of the first button as follows.

Here's the result of the above code.

Configuring Anchor Position

You can also position your Floating Action Button anchored to a certain view. The most common case is anchoring your Floating Action Button to AppBarLayout as follows.

Transforming to Menu / Toolbar

Floating Action Button is typically used to provide main action for your current view. When you have multiple main actions, it's a good idea to transform your Floating Action Button to display more available actions. To enable this transformation, you need to provide the list of available actions for your Floating Action Button. This can be done by binding the ItemsSource property of your Floating Action Button as follows.

And here's the definition in the ViewModel.

After binding the Floating Action Button, you can choose either FloatingActionButtonMenuType.Popup or FloatingActionButtonMenuType.Toolbar to display the additional actions.

The following code shows you how to show additional commands in menu view.

Here's the result.

On the other hand, if you want to show additional commands in the toolbar view, use the following code.

Here's the result.

Understanding Floating Action Behavior

The Material Fragment uses CoordinatorLayout as the main container for your view content, with the Floating Action Buttons being registered under the CoordinatorLayout. It's implemented this way because Floating Action Button is designed to react naturally whenever certain events occurred such as scrolling. Some of the built-in reactions or behaviors of Floating Action Button are as follows.

Slide up when ActionToastPresenter (a.k.a SnackBar) is shown

You can use ActionToastPresenter in the ViewModel to show a SnackBar as follows.

Additionally you can specify an action in ActionToastPresenter to provide quick action in regards to the toast context. The following code shows how you can add an action in ActionToastPresenter.

When the snack bar is shown, the Floating Action Button will slide up so that the content won't overlap.

Slide down when the content is scroll up, and immediately slide up when the content is scroll down

When you have a scrollable content with Floating Action Button, the Floating Action Button can somewhat hide the content of your view. To overcome this, you can enable hide on scroll up behavior as follows.

And here's the result.

Zoom out / zoom in when sliding content in view pager

When using view pager, you can have a page or fragment containing Floating Action Button. By default, this Floating Action Button will smoothly animate when user swipes the view pager to show next or previous content. The previous Floating Action Button will be hidden while the next Floating Action Button will be shown, if any.

Configuring Fragment Transitions

Transitions between different fragments involves enter and exit transitions that animated throughout the entire view hierarchies independent to each other. Example of such transitions are a fade transition, slide transition or the newly introduced explode transition. Crosslight Android Material fragments has predefined built-in transitions that are considered common in most mobile apps. These transitions might differ when the fragment is used inside master detail fragment or inside a view pager.

The following table explains the default fragment transition in each possible scenarios.

AnimationScenarioTransition
Enter AnimationBasic NavigationSlide + Fade Transition
Enter AnimationDrawer NavigationFade Transition
Enter AnimationMaster Detail NavigationNone
Enter AnimationInside a View PagerNone
Exit AnimationBasic NavigationFade
Exit AnimationMaster Detail NavigationNone
Exit AnimationInside a View PagerNone
Return AnimationBasic NavigationFade
Return AnimationMaster Detail NavigationNone
Return AnimationInside a View PagerNone
Reenter AnimationBasic NavigationFade
Reenter AnimationMaster Detail NavigationNone
Reenter AnimationInside a View PagerNone

To customize this animation, you can set the EnterAnimation, ExitAnimation, ReturnAnimation and ReenterAnimation as follows. Note that this transition only applicable with API Level 21+.

Enabling Shared Element Transitions

During fragment transitions, often times there are elements common to both fragments and providing the ability to transition these shared elements separately emphasizes continuity between transitions and breaks activity boundaries as the user navigates the app. To enable shared elements transitions, you need to let the Material Fragment know which is the source shared element in the source fragment and which is the target shared element in target fragment.

Specifying the source and target shared element is easy and straightforward. You only need to specify the control id at both of the fragment such as shown below. For example, here's the code for the source Fragment.

And here's in the target Fragment.

Notice that the SourceSharedElementIds and TargetSharedElementIds are collection type property. Therefore you can actually specify more than one shared elements and the mapping will use the index of item inside the collection. The first item inside SourceSharedElementIds will be transitioned to first item inside TargetSharedElementIds .

This configuration is applicable to most fragments except for FormFragment. In FormFragment scenario, it is considered that user can only transition a single image when navigating to a FormFragment. The following code shows how to enable shared element transition when navigating to a FormFragment.

Here's the code for the target FormFragment.

Configuring Basic Appearance

Material Fragment provides some basic appearance settings that you can use, eliminating the need to configure it in the layout's AXML file. You can find the basic appearance settings in Appearance property, accessible from the fragment. Using this Appearance property, you can set the background and padding of your view content.

Sample

To learn more about the above features in more detail, see ui-Material samples at http://git.intersoftpt.com/projects/CS/repos/ui-Material/browse.