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

wkh*_*tch 6 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];
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,当我打电话时,我得到与userUpLeft相同的值(在屏幕坐标中,而不是相对于父节点)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));
Run Code Online (Sandbox Code Playgroud)

我的理解是,一个arg调用等同于指定你想要翻译/移动到的结束坐标,而两个arg版本开始于...结束于,或者从...到我已经搞砸了两者都无法到达那里.

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

mat*_*ash 16

首先,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);
Run Code Online (Sandbox Code Playgroud)

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