确定ObjectAnimator的translationX / Y值;如何将视图移动到精确的屏幕位置?

时间:2014-06-14 06:42:59

标签: android android-layout objectanimator

我正在尝试使用ObjectAnimator.ofFloat(...)将视图移动到屏幕的右上角但是,我没有得到我期望的结果。我预先使用ViewTreeListener等获取视图的坐标,我已经知道我需要从整个宽度的末尾偏移的x值。我无法将任何一个维度移动到我想要的位置。相关代码:

获取起始坐标;目前的观点是:

int[] userCoords = new int[]{0,0};
userControlLayout.getLocationInWindow(userCoords);
//also tried getLocationInScreen(userCoords); same result
userUpLeft = userCoords[0];
userUpTop = userCoords[1];

令人惊讶的是,当我调用userControlLayout.getLeft()时,我获得的值与userUpLeft(在屏幕坐标中,而不是相对于父级)相同。我希望根据我对文档的理解,它们会有所不同。总之...

构建ObjectAnimators:

//testXTranslate is a magic number of 390 that works; arrived at by trial. no idea why that 
// value puts the view where I want it; can't find any correlation between the dimension 
// and measurements I've got
ObjectAnimator translateX = ObjectAnimator.ofFloat(userControlLayout, "translationX",
                                                                  testXTranslate);

//again, using another magic number of -410f puts me at the Y I want, but again, no idea //why; currently trying the two argument call, which I understand is from...to
//if userUpTop was derived using screen coordinates, then isn't it logical to assume that -//userUpTop would result in moving to Y 0, which is what I want? Doesn't happen
ObjectAnimator translateY = ObjectAnimator.ofFloat(userControlLayout, "translationY",
                                                                  userUpTop, -(userUpTop));

我的理解是,一个arg调用等同于指定要翻译/移动到的结束坐标,两个arg版本从...结束,或者从......到我开始与两者混乱,无法到达那里。

显然,我缺少非常基础的知识,只是试图找出究竟是什么。任何指导非常感谢。谢谢。

1 个答案:

答案 0 :(得分:16)

首先,userControlLayout.getLeft()与父视图相关。如果此父级与屏幕的左边缘对齐,则这些值将匹配。对于getTop(),它通常是不同的,因为getLocationInWindow()返回绝对坐标,这意味着y = 0是窗口的最左上角 - 即在操作栏后面。< / p>

通常,您希望将控件相对于其父级进行转换(因为如果它超出这些边界,它甚至不会被绘制)。因此,假设您想要将控件置于(targetX, targetY),您应该使用:

int deltaX = targetX - button.getLeft();
int deltaY = targetY - button.getTop();

ObjectAnimator translateX = ObjectAnimator.ofFloat(button, "translationX", deltaX);
ObjectAnimator translateY = ObjectAnimator.ofFloat(button, "translationY", deltaY);

当您向ObjectAnimator提供多个值时,您将在动画中指示中间值。因此,在您的情况下,userUpTop, -userUpTop会导致翻译首先降低,然后再降低。请记住,平移(以及旋转和所有其他变换)始终相对于原始位置。