简体   繁体   中英

How to show a Snackbar in Android on the top when using ConstraintLayout in a nice way

I am using ConstraintLayout in Android and I would like to display a Snackbar message at the top of the screen. I found this question on Stackoverflow: How to show Snackbar at top of the screen

The answer with the most likes is quite bad as it looks horrible because you can see the Snackbar beeing animated to the top:

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();

The second answer assumes that you are using a CorrdinatorLayout which I don't do

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();

Do you know how I can display the SnackBar in a ConstraintLayout on top in a nice way (meaning that it will just pop up at the top of the screen without being animated to the top)?

You can use the first piece of code and do the following:

Add this line to resolve the animation issue:

snackbar.setAnimationMode(BaseTransientBottomBar.ANIMATION_MODE_FADE);

If this doesn't works try this:

snackbar.setAnchorView(*mention viewId above whom you want to show SnackBar*)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM