我的布局与本教程完全相同。但在本教程中,我们在Fab中使用了app:layout_behavior="pl.michalz.hideonscrollexample.ScrollingFABBehavior",因此SnackBar涵盖了Fab。如果没有这段代码,Fab就不会移动,然后是RecyclerView。如何正确显示SnackBar?
Snackbar.make(getActivity().findViewById(R.id.coordinatorLayout),
adapter.getNewsList().get(position).getTitle(), Snackbar.LENGTH_LONG).show();发布于 2015-07-29 12:27:49
你所遵循的例子是非常不幸的。FloatingActionButton在CoordinatorLayout中的默认行为是在显示SnackBar时向上移动。由于这段代码覆盖了Behavior,所以失去了这个特性,因为这些方法从不调用它们的超类实现。显然,作者没有考虑过这一点。但是,您可以修改ScrollingFABBehavior以扩展原始的Behavior,从而支持SnackBar。
public class ScrollingFABBehavior extends FloatingActionButton.Behavior {
private int toolbarHeight;
public ScrollingFABBehavior(Context context, AttributeSet attrs) {
super();
this.toolbarHeight = Utils.getToolbarHeight(context);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
return super.layoutDependsOn(parent, fab, dependency) || (dependency instanceof AppBarLayout);
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
boolean returnValue = super.onDependentViewChanged(parent, fab, dependency);
if (dependency instanceof AppBarLayout) {
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
int distanceToScroll = fab.getHeight() + fabBottomMargin;
float ratio = (float)dependency.getY()/(float)toolbarHeight;
fab.setTranslationY(-distanceToScroll * ratio);
}
return returnValue;
}
} 这实际上是这个示例的https://github.com/mzgreen/HideOnScrollExample中的类,在我自己编写了相同的代码并想要测试它之后,我找到了它。他们只忘了更新博客文章:-/
发布于 2015-07-29 12:28:57
你试过这个吗?
...
View view = inflater.inlfate(R.layout.my_layout, parent, false);
...
Snackbar.make(view.findViewById(R.id.fab),
adapter.getNewsList().get(position).getTitle(), Snackbar.LENGTH_LONG).show();
...
return view;假设您在Fragment中调用了上面的代码,所以我添加了view变量来调用findViewById()方法。
https://stackoverflow.com/questions/31698670
复制相似问题