Hide FAB in NestedScrollView when scrolling

后端 未结 4 1433
误落风尘
误落风尘 2021-02-07 14:06

I am having a nestedscrollview with content like some linearlayouts and textviews. I am using a floatingactionbutton library for some reasons, as well. So I can\'t use any behav

4条回答
  •  礼貌的吻别
    2021-02-07 14:35

    Create FabScrollBehavior class

    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;
        }
    }
    

    Where AppUtil.getToolbarHeight(context) is -

    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;
        }
    

    then in your layout add to FloatingActionButton layout_behavior:

       
    

    The whole layout looks like

    
    
    
        
    
            
    
        
    
    
        
    
        
    
    
    
    

    Implemented from https://mzgreen.github.io/2015/02/15/How-to-hideshow-Toolbar-when-list-is-scroling(part1)/

提交回复
热议问题