【问题标题】:Determining translationX/Y values for ObjectAnimator; how to move a view to an exact screen position?确定 ObjectAnimator 的平移 X/Y 值;如何将视图移动到确切的屏幕位置?
【发布时间】:2014-06-14 15:00:47
【问题描述】:

我正在尝试使用 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 相同(在屏幕坐标中,而不是相对于父级),根据我对文档的理解,我希望它们会有所不同。总之……

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

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

【问题讨论】:

  • 好像translationX,translationY是relatice dx,dy

标签: android android-layout objectanimator


【解决方案1】:

首先,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(),它只会让我稍微向上移动,而不是靠近顶部的任何地方。我要移动的视图在一个片段中,并且有三个父级;所有宽度/高度都设置为填充父级...(续)
  • ...(续)我可以使用我提到的硬编码值将它移动到我想要的位置(这意味着它可以移动到它的父级之外),但不使用任何计算我可以访问的坐标和测量值。我是否需要询问父布局以获取更多信息,如果需要,怎么办?感谢回复
  • 您的问题得到答案了吗?问是因为我有同样的误解((
  • @kononger 抱歉,没有确定性。
猜你喜欢
  • 2017-01-22
  • 2017-07-24
  • 2021-02-23
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2021-05-28
相关资源
最近更新 更多