view.getX() != 0 时 ObjectAnimator 无法正常工作

ObjectAnimator not working properly when view.getX() != 0

我正在使用 ObjectAnimator 将视图水平平移到外部视图的右边缘。两个视图都是同一布局的子视图,第二个视图匹配父视图的宽度和高度并包含第一个视图。当我的 activity 启动并调用 ObjectAnimator 来平移视图时,它只会在视图从 0.0、0.0 开始时到达正确的目的地。当起始坐标为 100.00,100.00 时,视图结束时超出其应有位置 100.00 个单位。

startX = view.getX();
        endX = getRight(layout) - view.getWidth();
        Log.i("debugger", "going from  x="+startX+" to x="+endX);
        translateRight = ObjectAnimator.ofFloat(view, "translationX", startX, endX);

并在 animatorListener 中

@Override
        public void onAnimationEnd(Animator animator) {
            Log.i("debugger", "end x = "+view.getX());
        }

我用来获取视图右边缘X坐标的方法

public int getRight(View view){
    return (int)(view.getX()+view.getWidth());
}

xml

的片段
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="100"
    android:orientation="horizontal"
    android:gravity="center">
    <RelativeLayout
        android:layout_width="0dp"
        android:layout_weight="82"
        android:layout_height="match_parent">
        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/outerView"
            />
        <View
            android:layout_height="@dimen/view_width"
            android:layout_width="@dimen/view_width"
            android:background="@drawable/view"
            android:id="@+id/view"
            android:layout_toRightOf="@id/obstacle1"
            android:layout_below="@id/obstacle1"
            />
        <View
            android:id="@+id/obstacle1"
            android:layout_height="@dimen/view_width"
            android:layout_width="@dimen/view_width"
            android:background="@drawable/obstacle"
            android:layout_alignParentTop="true"
            />

layout

当视图从左上角(障碍物 1 所在的位置)开始时,视图最终与 outerView 的右内壁齐平,它应该在的位置。但是,当视图具有非零坐标时,如位于障碍物 1 下方和右侧的示例中,它会越过右边缘并与 outerView 的外墙齐平。有趣的是,如果将视图放在左上角的 xml 中,则无论它位于何处,它都可以按预期移动。当它不从角落开始时,一切都从一开始就被劫持了。

当视图从 0,0 开始时,日志如下所示:

going from x=0 to x=1080
end x = 1080

当视图从 100、100 开始时,日志如下所示:

going from x=100 to x=1080
end x = 1180

有人知道为什么会这样吗?任何帮助将不胜感激。

您正在 X 轴上平移视图,起始值为 100。如果视图的 translationX 属性为 0,则动画会立即将视图平移 100。

你应该这样做:

translateRight = ObjectAnimator.ofFloat(view, "translationX", view.getTranslationX(), endX - startX);