在 Android 中观看动画

View animation in Android

我有一个问题,不是我需要解释的问题。目前我在我的应用程序中有一个按钮,允许视图从工具栏下方向下滑动。在此视图中,有提供高级搜索功能的编辑文本等。

我创建了大小为 100dp 且上边距为 -100dp 的视图。这可以正常工作并隐藏视图。当我为下面的视图设置动画时,我的问题就更重要了。我"pushing"他们跟主视图打倒了。我认为向下和向上应该匹配但是我必须将第二个视图设置为 -30 的值才能正确重新对齐。

谁能解释一下?

注意 - 这是一个测试布局

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginTop="-100dp"
        android:background="#Fa45"
        android:id="@+id/viewtest">
</RelativeLayout>
<RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/contentMain">
       <Button
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center_horizontal"
           android:text="Slide Up" />
       <Button
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center_horizontal"
           android:text="Slide Down"
           android:layout_alignParentTop="true"
           android:layout_centerHorizontal="true" />
</RelativeLayout>

这不行

这是行不通的,我的意思是当按钮向右滑动到另一个视图时,按钮最终会丢失或半截断。

public void startSlideUpAnimation(View view) {
        v.animate().translationY(-400).setInterpolator(new BounceInterpolator()).setDuration(1000);
        x.animate().translationY(-400).setInterpolator(new BounceInterpolator()).setDuration(1000);
    }

public void startSlideDownAnimation(View view) {
    v.animate().translationY(400).setInterpolator(new BounceInterpolator()).setDuration(1000);
    x.animate().translationY(400).setInterpolator(new BounceInterpolator()).setDuration(1000);
}

但是如果我换行:

x.animate().translationY(-400).setInterpolator(new BounceInterpolator()).setDuration(1000);

x.animate().translationY(-30).setInterpolator(new BounceInterpolator()).setDuration(1000);

它工作得很好。我是疯了还是在胡扯数学?

编辑

好的,我发现如果我在两个视图上将平移 y 设置为 0,它们在返回和返回原点的过程中都完全匹配。这对我来说更没有意义,因为我认为浮点偏移量是它应该返回或翻译的值。

有什么想法吗?将它设置为零是真正让它回到原点还是我错过了一块拼图?

每个视图翻译值最初都是 zero 并且调用 translationY 将其发送到指定的绝对值。

如果要可以调用translationYBy将当前值偏移指定值

考虑到这个解释,如果您编写以下代码,您将通过动画到一个位置然后返回到 zero 原始位置来获得正确的结果。

// first
.translationY(-400) // translate to -400
// and then later
.translationY(0) // go back to the original position

或者如果您按照自己的想法行事,您可以像下面这样编写代码,从当前值转换 400 偏移量,然后将 400 偏移量转换到另一个方向

// first
.translationYBy(-400) // offset 400 to one direction
// and then later
.translationYBy(400) // offset 400 to the other direction

这里是官方文档:https://developer.android.com/reference/android/view/ViewPropertyAnimator.html