Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show Snackbar at top of the screen

As the Android documentation says

Snackbars provide lightweight feedback about an operation. They show a brief message at the bottom of the screen on mobile and lower left on larger devices.

Is there any alternative by which we can show snackbars at top of the screen instead of the bottom?

Right now I am doing something like this which shows a snackbar at the bottom of the screen.

Snackbar.make(findViewById(android.R.id.content), "Hello this is a snackbar!!!", 
Snackbar.LENGTH_LONG).setAction("Undo", mOnClickListener)
.setActionTextColor(Color.RED)
.show();
like image 645
Pankaj Avatar asked Jul 31 '15 12:07

Pankaj


3 Answers

It is possible to make the snackbar appear on top of the screen using this:

Snackbar snack = Snackbar.make(parentLayout, str, Snackbar.LENGTH_LONG);
View view = snack.getView();
FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
view.setLayoutParams(params);
snack.show();

From the OP:

I had to change the first line:

Snackbar snack = Snackbar.make(findViewById(android.R.id.content), "Had a snack at Snackbar", Snackbar.LENGTH_LONG);
like image 66
Adarsh Yadav Avatar answered Nov 16 '22 17:11

Adarsh Yadav


CoordinatorLayout coordinatorLayout=(CoordinatorLayout)findViewById(R.id.coordinatorLayout);
Snackbar snackbar = Snackbar.make(coordinatorLayout, "Text", Snackbar.LENGTH_LONG);
View view = snackbar.getView();
CoordinatorLayout.LayoutParams params=(CoordinatorLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
view.setLayoutParams(params);
snackbar.show();
like image 44
Vijayan R Avatar answered Nov 16 '22 17:11

Vijayan R


Kotlin-

    val snackBarView = Snackbar.make(view, "SnackBar Message" , Snackbar.LENGTH_LONG)
    val view = snackBarView.view
    val params = view.layoutParams as FrameLayout.LayoutParams
    params.gravity = Gravity.TOP
    view.layoutParams = params
    view.background = ContextCompat.getDrawable(context,R.drawable.custom_drawable) // for custom background
    snackBarView.animationMode = BaseTransientBottomBar.ANIMATION_MODE_FADE
    snackBarView.show()

below line will resolve the animation issue.

snackBarView.animationMode = BaseTransientBottomBar.ANIMATION_MODE_FADE

Alternate solution- snackBarView.anchorView = mention viewId above whom you want to show SnackBar

like image 24
Deepak Avatar answered Nov 16 '22 16:11

Deepak