Search code examples
androidmaterial-designandroiddesignsupportandroid-coordinatorlayoutandroid-snackbar

Move cardview on Snackbar - Co-ordinator layout


I have a custom textview in a cardview at the bottom of the screen and using snackbar to display error messages on logging in. Now when the snackbar shows, the sign up textview should move up. I have tried using co-ordinator layout but it does not work. This is the image enter image description here


Solution

  • You need to implement a layout behavior for your View and reference it from your layout xml file.

    It is simple to implement your own layout behavior. In your case, you only need to set the translation y of your view when the snackbar appears.

    public class YourCustomBehavior extends CoordinatorLayout.Behavior<View> {
    
        public YourCustomBehavior(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
            float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
            child.setTranslationY(translationY);
            return true;
        }
    
        @Override
        public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
            // we only want to trigger the change 
            // only when the changes is from a snackbar
            return dependency instanceof Snackbar.SnackbarLayout;
        }
    }
    

    And add it to your layout xml like this

    <android.support.v7.widget.CardView
            android:id="@+id/your_sign_up_card_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ...
            app:layout_behavior="com.your.app.YourCustomBehavior"/>
    

    The value for the app:layout_behavior attribute should be the full qualified name of the behavior class.

    You can also refer to this article which explains everything nicely.