简体   繁体   English

以一种不错的方式使用 ConstraintLayout 时,如何在顶部的 Android 中显示 Snackbar

[英]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.我在 Android 中使用 ConstraintLayout,我想在屏幕顶部显示一条 Snackbar 消息。 I found this question on Stackoverflow: How to show Snackbar at top of the screen我在 Stackoverflow 上发现了这个问题: 如何在屏幕顶部显示 Snackbar

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 的蜜蜂动画到顶部:

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第二个答案假设您使用的是我不使用的 CorrdinatorLayout

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)?你知道我怎样才能以一种很好的方式在顶部的 ConstraintLayout 中显示 SnackBar(这意味着它只会在屏幕顶部弹出而不被动画到顶部)?

You can use the first piece of code and do the following:您可以使用第一段代码并执行以下操作:

Add this line to resolve the animation issue:添加此行以解决 animation 问题:

snackbar.setAnimationMode(BaseTransientBottomBar.ANIMATION_MODE_FADE);

If this doesn't works try this:如果这不起作用,试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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