我有一个nestedscrollview,内容像一些linearlayouts和textviews.我也出于某些原因使用了floatingactionbutton库.所以我不能使用任何行为.我不知道如何处理scrollviewlistener从scrollview隐藏并像动作一样动态显示fab.
有什么建议如何在滚动时隐藏和显示晶圆厂?
简单地将以下代码添加到NestedScrollView ScrollChangeListener:
NestedScrollView nsv = v.findViewById(R.id.nsv); nsv.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { if (scrollY > oldScrollY) { fab.hide(); } else { fab.show(); } } });
创建FabScrollBehavior类
public class FabScrollBehavior extends CoordinatorLayout.Behavior{ private int toolbarHeight; public FabScrollBehavior(Context context, AttributeSet attrs) { super(context, attrs); this.toolbarHeight = AppUtil.getToolbarHeight(context); } @Override public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton fab, View dependency) { return dependency instanceof AppBarLayout; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View 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 true; } }
AppUtil.getToolbarHeight(context)的位置 -
public static int getToolbarHeight(Context context) { final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes( new int[]{R.attr.actionBarSize}); int toolbarHeight = (int) styledAttributes.getDimension(0, 0); styledAttributes.recycle(); return toolbarHeight; }
然后在你的布局中添加到FloatingActionButton layout_behavior:
整个布局看起来像
从https://mzgreen.github.io/2015/02/15/How-to-hideshow-Toolbar-when-list-is-scroling(part1)/实施