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

时间:2015-11-04 04:52:29

标签: java android view objectanimator

我正在使用ObjectAnimator将视图水平转换为外部视图的右边缘。两个视图都是相同布局的子视图,第二个视图匹配父视图的宽度和高度并包围第一个视图。当我的活动开始并调用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所在的位置)开始时,视图最终与外视图的内右壁齐平,应该在哪里。但是,当视图具有非零坐标时,如在它位于障碍物1的下方和右侧的示例中,它经过右边缘并与外视图的外壁齐平。有趣的是,如果视图放在左上角的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

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

1 个答案:

答案 0 :(得分:0)

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

你应该这样做:

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