8

我正在尝试使用 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];

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

构造 ObjectAnimator:

//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 版本开始于...结束于,或者,从...到我搞砸了两者都无法到达那里。

显然,我缺少非常基础的知识,只是想弄清楚那到底是什么。非常感谢任何指导。谢谢。

4

1 回答 1

20

First, userControlLayout.getLeft() is relative to the parent view. If this parent is aligned to the left edge of the screen, those values will match. For getTop() it's generally different simply because getLocationInWindow() returns absolute coordinates, which means that y = 0 is the very top left of the window -- i.e. behind the action bar.

Generally you want to translate the control relative to its parent (since it won't even be drawn if it moves outside those bounds). So supposing you want to position the control at (targetX, targetY), you should use:

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

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

When you supply multiple values to an ObjectAnimator, you're indicating intermediate values in the animation. So in your case userUpTop, -userUpTop would cause the translation to go down first and then up. Remember that translation (as well as rotation and all the other transformations) is always relative to the original position.

于 2014-06-14T07:00:47.313 回答