[英]SnackBar covers FAB
我的布局與本教程完全相同。 但是在本教程中,我們在Fab XML中使用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();
您遵循的示例非常不幸。 當您顯示SnackBar
時, CoordinatorLayout
中FloatingActionButton
的默認行為是向上移動。 由於此代碼將覆蓋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;
}
}
這實際上是示例的github存儲庫中的類 ,我在自己編寫相同的代碼並想要對其進行測試之后就找到了它。 他們只忘記更新博客文章:-/
你有嘗試過嗎?
...
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()
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.