如何像浮动按钮一样在 Snackbar 上方移动视图

How to move a view above Snackbar just like FloatingButton

我有一个线性布局,我想在 Snackbar 出现时向上移动。

我看到了很多如何使用浮动按钮执行此操作的示例,但是常规视图呢?

不需要 Co-ordinator 布局 使用常规视图将快餐栏对齐到视图的底部,并在单击按钮时将按钮放在它上面无论您的逻辑是什么,都显示小吃店或线性布局。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
/*snackbar code

 <LinearLayout
            android:id="@+id/linear_snack bar"
            android:layout_width="match_parent"
            android:layout_height="@dimen/margin_45"
            android:layout_alignParentBottom="true"
            android:layout_marginTop="@dimen/margin_0"
            android:background="@color/dark_grey">

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@color/orange"
                android:gravity="center"
                android:textColor="@color/white"
                android:textSize="@dimen/text_size_h7" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:textSize="@dimen/text_size_h7" />
        </LinearLayout>

<View  android:layout_above="@+id/linear_snack bar"



</RelativeLayout>

您需要向 LinearLayout 添加行为并将其嵌入 CoordinatorLayout。您可能想阅读以下内容:http://alisonhuang-blog.logdown.com/posts/290009-design-support-library-coordinator-layout-and-behavior

我将详细说明已批准的答案,因为我认为有一个比该文章提供的实现稍微简单的实现。

我无法找到处理一般视图移动的内置行为,但这是一个很好的通用选项(来自 http://alisonhuang-blog.logdown.com/posts/290009-design-support-library-coordinator-layout-and-behavior 在另一条评论中链接):

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<View> {

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

然后,在您的布局文件中添加一个 layout_behavior,如下所示:

<LinearLayout
    android:id="@+id/main_content"
    android:orientation="vertical"
    app:layout_behavior="com.example.MoveUpwardBehavior"/>

其中 layout_behavior 是自定义行为的完整路径。没有必要继承 LinearLayout 除非你有一个特定的需要有一个默认的行为,这似乎并不常见。

我实现了这个,发现当 snackbar 消失时,视图在 snackbars 的地方仍然保持白色 space,显然如果设备上的动画被禁用,这是已知的。

为了解决这个问题,我更改了 onDependentViewChanged 方法来存储此行为附加到的视图的初始 Y 位置。然后在移除 snackbar 时将该视图的位置重置为存储的 Y 位置

private static float initialPositionY;

@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
    initialPositionY = child.getY();
    float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight());
    child.setTranslationY(translationY);
    return true;
}

@Override
public void onDependentViewRemoved(CoordinatorLayout parent, View child, View dependency) {
    super.onDependentViewRemoved(parent, child, dependency);
    child.setTranslationY(initialPositionY);
}

除了 Travis Castillo 的回答: 要允许在 onDependentViewChanged() 内触发连续的 SnackBar,您必须取消由 onDependentViewRemoved():

启动的任何可能正在进行的动画
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
    float translationY = Math.min(0, ViewCompat.getTranslationY(dependency) - dependency.getHeight());
    ViewCompat.animate(child).cancel(); //cancel potential animation started in onDependentViewRemoved()
    ViewCompat.setTranslationY(child, translationY);
    return true;
}

如果不取消,当一个 SnackBar 被另一个 SnackBar 替换时,LinearLayout 将跳到第二个 SnackBar 下面。

基于@Travis Castillo 的回答。修正问题如:

  • 向上移动整个布局并导致视图顶部的对象消失。
  • 在彼此紧接着显示 SnackBar 时不会上推布局。

所以这里是 MoveUpwardBehavior Class 的固定代码:

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<View> {

    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());

        //Dismiss last SnackBar immediately to prevent from conflict when showing SnackBars immediately after eachother
        ViewCompat.animate(child).cancel();

        //Move entire child layout up that causes objects on top disappear
        ViewCompat.setTranslationY(child, translationY);

        //Set top padding to child layout to reappear missing objects
        //If you had set padding to child in xml, then you have to set them here by <child.getPaddingLeft(), ...>
        child.setPadding(0, -Math.round(translationY), 0, 0);

        return true;
    }

    @Override
    public void onDependentViewRemoved(CoordinatorLayout parent, View child, View dependency) {

        //Reset paddings and translationY to its default
        child.setPadding(0, 0, 0, 0);
        ViewCompat.animate(child).translationY(0).start();

    }
}

此代码会推送用户在屏幕上看到的内容,此外,当 SnackBar 显示时,用户可以访问布局中的所有对象。

如果您希望 SnackBar 覆盖对象而不是推送对象,而且用户确实可以访问所有对象,那么您需要更改方法 onDependentViewChanged:

@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
    float translationY = Math.min(0, ViewCompat.getTranslationY(dependency) - dependency.getHeight());

    //Dismiss last SnackBar immediately to prevent from conflict when showing SnackBars immediately after eachother
    ViewCompat.animate(child).cancel();

    //Padding from bottom instead pushing top and padding from top.
    //If you had set padding to child in xml, then you have to set them here by <child.getPaddingLeft(), ...>
    child.setPadding(0, 0, 0, -Math.round(translationY));

    return true;
}

和方法onDependentViewRemoved:

@Override
public void onDependentViewRemoved(CoordinatorLayout parent, View child, View dependency) {

    //Reset paddings and translationY to its default
    child.setPadding(0, 0, 0, 0);

}

不幸的是,当用户滑动以移除时您将失去动画 SnackBar。并且您必须使用 ValueAnimator class 为填充更改制作动画,这会在此处产生一些冲突,您必须对其进行调试。

https://developer.android.com/reference/android/animation/ValueAnimator.html

任何关于滑动删除动画的评论SnackBar表示赞赏。

如果您可以跳过该动画,那么您就可以使用它。

总之还是推荐第一种

我编写了一个库,可以添加额外的视图以使用 SnackProgressBar 进行动画处理。它还包括 progressBar 和其他东西。试试看 https://github.com/tingyik90/snackprogressbar

假设您有以下要制作动画的视图。

View[] views = {view1, view2, view3};

在您的 activity 中创建一个 SnackProgressBarManager 实例,并包含要设置动画的视图。

SnackProgressBarManager snackProgressBarManager = new SnackProgressBarManager(rootView)
        .setViewsToMove(views)

当显示或关闭 SnackProgressBar 时,这些视图将相应地设置动画。

进一步改进 Travis Castillo 的回答。
这修复了卡顿动画 + 转换为 Kotlin。

无需手动进行 Y 翻译,因为它是自动处理的。
手动进行 Y 平移实际上会使动画看起来很卡。

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<View>(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)
    }
}

@Markymark 提出了很好的解决方案,但是在 snackbar 的第一帧上有 translationY==0,在第二个 translationY==full height 上并开始正确下降,因此依赖布局在第一帧上出现卡顿。这可以通过跳过第一帧 + 恢复原始填充作为良好的副作用来解决。

class MoveUpwardBehavior(context: Context?, attrs: AttributeSet?) : CoordinatorLayout.Behavior<View>(context, attrs), Parcelable {

    var originalPadding = -1

    constructor(parcel: Parcel) : this(
        TODO("context"),
        TODO("attrs")
    ) {
    }

    override fun layoutDependsOn(parent: CoordinatorLayout, targetView: View, snackBar: View): Boolean {
        return snackBar is Snackbar.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 {

        if (originalPadding==-1) {
            originalPadding = targetView.paddingBottom
            return true
        }
        val bottomPadding = min(0f, snackBar.translationY - snackBar.height).roundToInt()
//        println("bottomPadding: ${snackBar.translationY} ${snackBar.height}")

        //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-originalPadding))

        return true
    }

    override fun onDependentViewRemoved(parent: CoordinatorLayout, targetView: View, snackBar: View) {
        //Reset padding to default value
        targetView.setPadding(targetView.paddingLeft, targetView.paddingTop, targetView.paddingRight, originalPadding)
        originalPadding = -1
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {

    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<MoveUpwardBehavior> {
        override fun createFromParcel(parcel: Parcel): MoveUpwardBehavior {
            return MoveUpwardBehavior(parcel)
        }

        override fun newArray(size: Int): Array<MoveUpwardBehavior?> {
            return arrayOfNulls(size)
        }
    }
}