Android snackbar custom view

Android Snackbar Example

Android Snackbar is an interesting component introduced by Material Design. Snackbars are just like Toast messages except they provide action to interact with. Snackbar will be displayed at the bottom of the screen and can be swiped off in order to dismiss them.

Difference between Toast and Snackbar

  • Toast messages can be customized and printed anywhere on the screen, but a Snackbar can be only shown in the bottom of the screen.
  • A Toast message doesn’t have action button, but Snackbar may have action button optionally.
  • Toast message cannot be off until the time limit finish, but Snackbar can be swiped off before the time limit.

You can set how long the message will be shown using this three different values.

  • Snackbar.LENGTH_LONG
  • Snackbar.LENGTH_SHORT
  • Snackbar.LENGTH_INDEFINITE

Let’s Getting into Snackbar Android Example

In Android Studio, Create New Project and fill all the details required to create a new project.

Open build.gradle and add Material Design dependency.

By using material dependency, you can also create components like Recyclerview, Cardview and snackbar etc. If you want to know more about other material components check below links.

Also, setup the application theme as theme.MaterialComponents.

Now, done with the project setup.

Create Simple Android Snackbar

Below is the syntax of a simple snackbar. The make function accepts three parameters. View, display message and duration of the message to be displayed.

Android Snackbar with Action Callback

You can also mention a callback interaction method using setAction() method. This allows us to take certain action when the user interacts with the snackbar.

Customizing the Android Snackbar

Snackbar comes with default white color text and #323232 background color. You can override these colors.

Theming snackbars

Snackbars support Material Theming and can be customized in terms of color and typography.

Implementing snackbar theming

Using theme attributes in res/values/styles.xml

or in code (affects only this snackbar):

Android snackbar example

Download the example from github.

Thanks for reading this post. Material design having lot of useful components like Material Button , Cardview etc. I will write more about material design in my future post.

Источник

Android snackbar custom view

Android Custom Snackbar

Android custom snackbar is derived from the android default snackbar control

  • Use it in Activity or Fragment
  • Change the background and text color easily
  • Custom view applies in the snackbar control
  • Typeface applies easily on text
  • Corner radius and Padding applies
  • Androidx supported
  • More to find out yourself

Custom snackbar same as Default Control of the android Snackbar

Make background semi-transparent and add corner radius for the better look

Custom view according to your requirements

Читайте также:  Как идентифицировать андроид устройство

Apply gradient in the snackbar background

Refer This Sample Code

For, the more infromation refer this sample code here

With Coordinator Layout

Passing the activity context and coordinator layout as view in the custom snackbar constractor as shown below

Without Coordinator Layout

Only pass the activity context in the custom snackbar constractor as shown below

Function Parameter Description
actionTextColor Integer Color Value Change the action button text color, default value is colorAccent
actionTextColorRes Color Resource Refer actionTextColor function description
textColor Integer Color Value Change the message text color, default value is white color
textColorRes Color Resource Refer textColor function description
backgroundColor Integer Color Value Change the background color of the snackbar, default value is same as snackbar background also you can’t make it transparent
backgroundColorRes Color Resource Refer backgroundColor function description
cornerRadius Float Value Apply corner radius all the side (Left, Top, Right, Bottom), default value is 0
cornerRadiusRes Dimension Resource Refer cornerRadius function description
border Width as Integer and Integer Color Value Apply border width and color around the snackbar, default value of the width is 0 and color is transparent
borderRes Width as Dimension Resource and Color Resource Refer border function description
customView View or Layout Resource set the your customized view as snackbar, default value is null also when you apply custom view then other api are not in use as shown in the example code
message String set the message as string and default value is empty string
messageRes String Resource Refer message function description
duration Integer Value set the time duration default value is Snackbar.LENGTH_SHORT
padding Integer Value apply the padding at the (Left, Right, Bottom) side, default value is 0
paddingRes Dimension Resource Refer padding function description
textTypeface Typeface Change the message text Typeface, default value is Typeface.NORMAL
actionTypeface Typeface Change the action button text Typeface, default value is Typeface.NORMAL
withAction String Resource or String and Snackbar as anonymous function pass the first argument as action button name and default value is empty string, second argument as lamda function with snackbar reference
withCustomView View as anonymous function when custom view initialze then passing here for your further use
drawable GradientDrawable set the gradient drawable as snackbar background, default value is null also when you apply drawable then background color, cornerRadius, border width and color api are not in use as shown in the example code
drawableRes Drawable Resource Refer drawable function description
show Void Or Koltin DSL Show the snackbar view
dismiss Void Or Unit Dismiss the snackbar view
getView Void and return View? Same as withCustomView but it will return null value too

Kishan Donga (@ikishan92)
I am mobility developer.

Источник

Material Design Snackbar in Android – How and When to Use

by Suleiman · Published January 24, 2017 · Updated December 31, 2019

Snackbar was introduced in Material Design. It is available via the Design Support Library. Code-wise, it is similar to a Toast.

In this article, we’ll first clear the confusion around using Snackbar and Toast . Next, we’ll look at implementation and customizing.

But before that, let’s clarify what exactly a Snackbar is.

What is Snackbar?

A lightweight component that gives feedback to users. It optionally provides an action to users.

Behavior

Snackbars are displayed at the bottom of the screen. It stays there for the specified interval. Or, you can dismiss it by swiping.

However, there arises a confusion with our ‘ol pal, the Toast .

Snackbar VS Toast Confusion

The addition of a Snackbar created ambiguity. When do we use it and when to use Toast ?

Its important that we know what to use when. So before moving on to actual code implementation, let’s clear the confusion.

The Difference

Snackbar

Contain a single line of text directly related to the operation performed. They may contain a text action, but no icons.

  1. Lightweight feedback about an operation
  2. Optionally includes a single action
  3. Can optionally stay on-screen permanently, until swiped off screen

Toast

Primarily used for system messaging. They also display at the bottom of the screen, but may not be swiped off-screen.

  1. System-level messaging
  2. No user action can be performed
  3. Can only stay on screen temporarily. Cannot be swiped

Moving forward

Now that we’re clear about difference between the two, we can start implementing.

First, we’ll look at using a simple usage, right off the bat. Next I’ll tell you how to include a primary action. Then we’ll learn how to style it. Finally, we’ll go over its do’s and don’ts.

Usage

Displaying is relatively simple. In fact, it is similar to how you would write a Toast . We use the class android.support.design.widget.Snackbar .

The view (1st parameter) doesn’t have to be your parent layout. It can be any View .

TIP
Ideally, Snackbar works best if your parent layout is a CoordinatorLayout . This ensures that it plays nice with other UI elements (such as FAB). More on that later.

Next, the duration for displaying (3rd parameter), can be any of the following:

  1. LENGTH_INDEFINITE
  2. LENGTH_LONG
  3. LENGTH_SHORT

I hope the duration types above are self-explanatory.

LENGTH_INDEFINITE will show the Snackbar for and indefinite period of time. But you can dismiss it by swiping.

Finally, don’t forget to call Snackbar.show() .

NOTE
For Snackbar to work, your Activity must inherit from (extend) AppCompatActivity . Otherwise, consider a third-party alternative.

Adding a Primary Action

As stated in the Material Design spec, we can optionally include an action.

Adding a user action is relatively simple. Simply modify your existing call as follows.

Ideal use-cases for a primary action include:

  • UNDO – for deleted message, archive, etc
  • CONNECT – to enable internet if disconnected
  • RETRY – an action that failed (e.g. API call)

NOTE
Do not include an action for DISMISS. This is of no use. Just auto-dismiss your Snackbar by setting a short duration. Or it can simply be swiped away.

Styling

The Snackbar class follows the Builder pattern which allows for easy styling.

Action Text color

To style properties such as text colors, you’ll have to fetch the View first.

Then get the TextView from it.

Background color

First, you’ll need a reference. Then apply all your style properties and finally call snackbar.show() .

Playing nice with Floating Action Button

Have you seen this behavior before?

The FAB translates up, giving space for the Snackbar to rise from the bottom.

This is the ideal, recommended behavior. Because the last thing we want is the FAB overlap!

So to avoid that, just keep one thing in mind.

Your parent layout (root layout) must be a CoordinatorLayout . It ensures that the correct Behavior is applied to its child Views. In other words, it ensures that UI elements ‘behave’ or ‘coordinate’ correctly.

Here’s an example of how such an XML layout would look like.

Creating a Custom Layout

With v25.1.0 of Android Design Support Library, creating a custom layout is now possible.

That’s right, I’m talking about creating an XML layout of your own.

We can do this in 4 simple steps.

1. Create XML layout

Now I’m going to leave this to you. Let loose your imagination!

As for me, I’ll just roll in a simple layout this time.

2. Create a Custom class

Create a CustomSnackbar final class that extends BaseTransientBottomBar .

Next, create an inner, static class ContentViewCallback. Implement the BaseTransientBottomBar.ContentViewCallback interface.

Now, our main layout is inflated and taken care of. Next is handling the TextView and action Button .

But keep in mind that a typical Snackbar has this. Moreover, since my custom layout has a Text and Button too, I’m adding functionality to it.

So if you don’t have either of those Views, then skip ahead to point 4.

3. Inflate Custom View

Create a static method make(ViewGroup parent, int duration) , similar to the original Snackbar . make() method.

Here, we will inflate our custom layout, using the parent ViewGroup .

4. Display it

Finally, you can display your CustomSnackbar, just like you would with a regular Snackbar .

CustomSnackbar.java

Here’s the complete code for the CustomSnackbar class.

Do’s and Don’ts

Knowing how to use Snackbar is essential. But knowing when to use it is important as well. So before we call this a wrap, let’s look at some do’s and don’ts.

Do

  1. keep the text content short
  2. Allow undoable actions to be undone (delete, archive, etc.)
  3. display feedback results for user actions
  4. style it to match your design

Don’t

  1. include icons
  2. perform core functionality via the action button
  3. display multiple instances
  4. display important system information or errors
  5. overlap or block the FAB (Floating Action Button)
  6. animate or reposition

Conclusion

The Snackbar is comparatively a tiny component in the Material Design spec. Hence it is easily prone to misunderstanding and misuse.

Giving users feedback is important. Effectively using it is key to your app.

Quick Recap

First, we clarified the difference between a Snackbar and Toast. Then we even discussed when to use what.

Next, we looked into using a simple implementation and went onto adding actions. From there, we looked into styling and customization options.

Additionally, we saw that even a custom layout can be used. Finally, we reinforced key guidelines.

Where to from here?

This is just one of the many new additions to Material Design.

The Design Support Library is making life easy for Android Developers to use Material Design. Are you using it?

Recommended Read:

I hope this article instilled a complete understanding about Snackbar .

Lastly, I’d like to hear your thoughts. Have anything to add to this? Or have I missed out anything? Drop ‘em in the comments below.

If you liked reading this article, share it on social media!

Product Designer who occasionally writes code.

Источник

Читайте также:  Apple airport utility android
Оцените статью