How to move a view above Snackbar just like FloatingButton

前端 未结 8 629
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 07:50

I got a linear layout that I want to move up when a Snackbar appears.

I saw many examples how to do this with FloatingButton, but what about a regular view?

8条回答
  •  野性不改
    2021-01-31 08:35

    I'm going to elaborate on the approved answer because I think there's a slightly simpler implementation than that article provides.

    I wasn't able to find a built-in behavior that handles a generic moving of views, but this one is a good general purpose option (from http://alisonhuang-blog.logdown.com/posts/290009-design-support-library-coordinator-layout-and-behavior linked in another comment):

    import android.content.Context;
    import android.support.annotation.Keep;
    import android.support.design.widget.CoordinatorLayout;
    import android.support.design.widget.Snackbar;
    import android.support.v4.view.ViewCompat;
    import android.util.AttributeSet;
    import android.view.View;
    
    @Keep
    public class MoveUpwardBehavior extends CoordinatorLayout.Behavior {
    
        public MoveUpwardBehavior() {
            super();
        }
    
        public MoveUpwardBehavior(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
            return dependency instanceof Snackbar.SnackbarLayout;
        }
    
        @Override
        public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
            float translationY = Math.min(0, ViewCompat.getTranslationY(dependency) - dependency.getHeight());
            ViewCompat.setTranslationY(child, translationY);
            return true;
        }
    
        //you need this when you swipe the snackbar(thanx to ubuntudroid's comment)
        @Override
        public void onDependentViewRemoved(CoordinatorLayout parent, View child, View dependency) {
            ViewCompat.animate(child).translationY(0).start();
        }
    }
    

    then, in your layout file add a layout_behavior as below:

    
    

    where the layout_behavior is the full path to your custom behavior. There's no need to subclass LinearLayout unless you have a specific need to have a default behavior, which seems uncommon.

提交回复
热议问题