正如标题所说,我想了解该方法到底在做什么。
首先我已经仔细检查过 android 的坐标系统是这样工作的: coordinate system
次要 - 请花一点时间检查我的 android studio 屏幕和方法快速文档。为什么我的 View 值(点击后)是 106? android screen
最佳答案
坐标系正确。
getY()
将返回顶部的值 View
+ Y 翻译。所以,如果getY()
正在返回 106 并且您将翻译 y 设置为 10,您的 View 顶部应该在 96。也可以尝试调用 getTop()
并检查那个值是多少
翻译是应用于 View
位置的偏移量.如果布局放置您的 View
在 x;y
你调用setTranslationY(10)
, 你的 View
将出现在 x;y+10
.这是一种控制 View
位置的方法布局后
额外提示,不要记录所有内容,而是使用调试器
如果你对位置和翻译之间的区别还有疑问,你可以试试这个,创建一个空的 Activity 并设置这个布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lelloman.dummy.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="asd asd"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="asd"/>
</RelativeLayout>
然后,您将看到 TextView
就在 Button
的正上方,因为这就是 RelativeLayout
的方式将定位 View
给定这些布局参数。现在,尝试调用
findViewById(R.id.button).setTranslationY(100);
您会注意到按钮将向下移动 100 像素,但是 TextView
仍将位于旧位置,因为翻译是在布局之后应用的。这是特定于 View
的东西View
的定位没有考虑到这一点在其父级内
您还可以在 xml 中设置翻译
<Button
android:translationY="100px"
...
关于android - 理解 View.setTranslationY() [/X() ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44434383/