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?
A further improvement Travis Castillo's answer.
This fixes the janky animation + converts to Kotlin.
There is no need to manually do a Y translation since it's handled automatically.
Manually doing the Y translation actually makes the animation look janky.
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.annotation.Keep
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import com.google.android.material.snackbar.Snackbar.SnackbarLayout
import kotlin.math.min
import kotlin.math.roundToInt
/**
* To use this, the parent container must be a CoordinatorLayout.
* This can be applied to a child ViewGroup with app:layout_behavior="com.example.MoveUpwardBehavior"
*/
@Keep
class MoveUpwardBehavior(context: Context?, attrs: AttributeSet?) : CoordinatorLayout.Behavior(context, attrs) {
override fun layoutDependsOn(parent: CoordinatorLayout, targetView: View, snackBar: View): Boolean {
return snackBar is SnackbarLayout
}
/**
* @param parent - the parent container
* @param targetView - the view that applies the layout_behavior
* @param snackBar
*/
override fun onDependentViewChanged(parent: CoordinatorLayout, targetView: View, snackBar: View): Boolean {
val bottomPadding = min(0f, snackBar.translationY - snackBar.height).roundToInt()
//Dismiss last SnackBar immediately to prevent from conflict when showing SnackBars immediately after each other
ViewCompat.animate(targetView).cancel()
//Set bottom padding so the target ViewGroup is not hidden
targetView.setPadding(targetView.paddingLeft, targetView.paddingTop, targetView.paddingRight, -bottomPadding)
return true
}
override fun onDependentViewRemoved(parent: CoordinatorLayout, targetView: View, snackBar: View) {
//Reset padding to default value
targetView.setPadding(targetView.paddingLeft, targetView.paddingTop, targetView.paddingRight, 0)
}
}