了解View.setTranslationY()[/ X()]

Ita*_*hen 3 user-interface android

如标题所示,我想了解该方法到底在做什么。

首先,我已经仔细检查过android的坐标系是这样的: 坐标系

辅助-请花一点时间检查我的android studio屏幕,以及方法快速文档。为什么我的视图(单击后)的值是106? android屏幕

lel*_*man 7

坐标系正确。

getY()将返回View+ Y转换的顶部的值。因此,如果getY()返回106并将平移y设置为10,则视图的顶部应位于96。尝试也调用getTop()并检查该值是多少

平移是应用于的位置的偏移量View。如果版式将您View放在x;y并致电setTranslationY(10),您View将出现在x;y+10。这是一种控制View布局后位置的方法

红利提示,而不是记录所有内容,请使用调试器

如果您仍然对位置和平移之间的差异有疑问,可以尝试一下,创建一个空的活动并设置此布局

<?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>
Run Code Online (Sandbox Code Playgroud)

然后,您将看到,位于的TextView正上方Button,因为RelativeLayoutView给定这些布局参数的情况下,这就是的位置。现在,尝试致电

findViewById(R.id.button).setTranslationY(100);
Run Code Online (Sandbox Code Playgroud)

您会注意到该按钮将向下移动100px,但该按钮仍将TextView位于旧位置,因为转换是在布局之后应用的。它是特定于它的东西View,而View在其父项中的位置并未考虑在内

您还可以使用以下命令在xml中设置翻译

<Button
    android:translationY="100px"
    ...
Run Code Online (Sandbox Code Playgroud)