Sunday, 7 August 2016

Custom SnackBar in Android

In ancient days , we were talking about the Toast. Using Toast we were showing the messages , useful information to the user.
But now a days, Toast has been replaced by the SnackBar, a powerful feature using which we can display messages to the user in an unique and attractive style.
Snackbar comes with a default animation from bottom to up and hide from top to bottom.
Like Toast , we can customize the Snackbar as well, which we will disucss now.
Note :
To access the SnackBar , The design library should be added in Android Studio project.
Steps to add the Design Library:
1. In Android Studio, Open you Module.
2. Now open the .gradle file.
3. and then add the design library under dependencies section like below.
Have a look at a design library in Bold
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
}
Snack Bar in Fragment:
When we showing the Snack bar in Fragment, many of us facing an issue as highlighted in below image.

Screenshot_20160807-014106

This situation arises when we are displaying the Snack Bar as below.
Snackbar.make(view.getRootView(), "This is a wrong SnackBar", Snackbar.LENGTH_LONG).show();
And to overcome this problem , the one should use the root layout id in place of view.getRootView() as follows
Snackbar.make(mView.findViewById(R.id.top_layout), "This is a correct SnackBar", Snackbar.LENGTH_LONG).show();
where R.id.top_layout is the parent element of your layout.

No comments:

Post a Comment