如何像在FloatingButton中一样移动Snackbar上方的视图

时间:2015-10-19 14:37:23

标签: android android-snackbar

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

我看了很多关于如何使用FloatingButton执行此操作的示例,但是常规视图呢?

9 个答案:

答案 0 :(得分:66)

我将详细阐述已批准的答案,因为我认为实施的实施比该文章提供的要简单得多。

我无法找到处理视图通用移动的内置行为,但这个是一个很好的通用选项(来自另一个评论中链接的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进行子类化,这似乎并不常见。

答案 1 :(得分:15)

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

答案 2 :(得分:15)

基于@Travis Castillo的回答。修复了以下问题:

Moving entire layout up and cause the objects on top of view disappear.
Doesnt push the layout up when showing SnackBars immediately after eachother.

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

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 类为填充更改制作动画,这会导致一些冲突,你必须调试它们。

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

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

如果您可以跳过该动画,则可以使用它。

无论如何,我建议先输入。

答案 3 :(得分:3)

我实现了这一点,发现当小吃店消失时,小吃店里的视图仍然留有白色空间,显然,如果设备上的动画已被禁用,则会知道这一点。

要解决此问题,我更改了onDependentViewChanged方法以存储此行为附加到的视图的初始Y位置。然后在移除小吃栏时将该视图的位置重置为存储的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);
}

答案 4 :(得分:1)

除了Travis Castillo的回答: 要允许在onDependentViewChanged()内触发连续的SnackBars,您必须取消由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之下。

答案 5 :(得分:0)

我已经编写了一个库,可以使用SnackProgressBar将其他视图添加到动画中。它还包括progressBar和其他东西。试一试https://github.com/tingyik90/snackprogressbar

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

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

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

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

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

答案 6 :(得分:0)

进一步改进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)
    }
}

答案 7 :(得分:0)

@Markymark 提出了很好的解决方案,但是在小吃店的第一帧上,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)
        }
    }
}

答案 8 :(得分:-4)

不需要协调员布局使用常规视图将小吃店对齐到视图的底部,并将按钮放在其上,点击按钮,无论您的逻辑是什么显示零食店或线性布局。

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