Make Snackbar push view upwards

Simon picture Simon · Nov 14, 2015 · Viewed 8.4k times · Source

Is there a way to make the snackbar push the view upwards when it is shown?

snackbar

Currently, when the snackbar is shown, it overlays the view below so it looks like half the button is cut off but I want it to almost "adjustPan" similar to the way that the softkeyboard works when it is shown on the screen.

Does anyone know of any tricks to achieve this?

Answer

sourcerebels picture sourcerebels · Nov 14, 2015

Put your view inside a android.support.design.CoordinatorLayout

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true">

    <View
        android:id="@+id/my_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_behavior="com.example.FloatingActionButtonBehavior"/>

</android.support.design.widget.CoordinatorLayout>

The important part here is app:layout_behavior attribute. Here is implementing class:

public class FloatingActionButtonBehavior extends CoordinatorLayout.Behavior<FloatingActionButton> {

    public FloatingActionButtonBehavior(Context context, AttributeSet attrs) {
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) {

        return dependency instanceof SnackbarLayout;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) {

        float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
        child.setTranslationY(translationY);
        return true;
    }
}

Then when you show the snackbar pass the reference to the CoordinatorLayout:

CoordinatorLayout coordinator = findViewById(R.id.coordinator);
Snackbar.make(coordinator, textResId, Snackbar.LENGTH_LONG)
        .setAction(R.string.accept_ok, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        })
        .setDuration(Snackbar.LENGTH_INDEFINITE)
        .show();

Hope this will help you.