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

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];

令人惊讶的是,当我调用userControlLayout.getLeft()时,我得到了与屏幕坐标相同的值(而不是相对于父级的值)。根据文档的理解,我本应该得到不同的值。无论如何...

构建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));

我的理解是,使用一个参数的调用等同于指定您要平移/移动到的结束坐标,而使用两个参数的版本则是从...到,或者从起始点...到终点。我已经尝试过两种方法,但都不行。

显然,我缺乏非常基本的知识,只是想找出确切的问题所在。任何指导都将不胜感激。谢谢。


看起来 translationX,translationY 是相对于 dx,dy 的。 - Michał Ziobro
1个回答

20

首先,userControlLayout.getLeft() 是相对于父视图的位置。如果这个父视图与屏幕左侧对齐,那么这些值将匹配。而对于 getTop(),通常情况下不同,因为 getLocationInWindow() 返回的是绝对坐标,这意味着 y=0 是窗口的最上方左侧,即在操作栏后面。

通常情况下,您希望将控件相对于其父级定位(因为如果移动到超出这些边界,它甚至都不会被绘制)。所以,假设您要将控件定位在 (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将导致首先向下移动,然后向上移动。请记住,平移(以及旋转和所有其他变换)始终是相对于原始位置的。


谢谢,@matiash。userControlLayout.getTop() 返回的值与 getLocationInWindow 相同;它们没有区别。因此,仅使用 Y 坐标进行讨论,我想将其移动到 0;一直到顶部(这里没有操作栏)。如果我使用 0 - userControlLayout.getTop(),它只会稍微把我往上移动,离顶部还有很远。我想要移动的视图在一个片段中,并且有三个父级;所有父级的宽度/高度都设置为填充父级... - wkhatch
我可以使用我提到的硬编码值将其移动到想要的位置(这意味着它可以移动到其父级之外),但无法使用我可以访问的坐标和测量计算。我需要查询父布局以获取更多信息吗?如果是这样,需要查询哪些信息?感谢您的回复。 - wkhatch
你有关于你的问题得到答案了吗?问这个是因为我也有同样的误解。 - konunger
@konunger 抱歉,没有明确的答案。 - wkhatch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接