android - 理解 View.setTranslationY() [/X() ]

标签 android user-interface

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

首先我已经仔细检查过 android 的坐标系统是这样工作的: coordinate system

次要 - 请花一点时间检查我的 android studio 屏幕和方法快速文档。为什么我的 View 值(点击后)是 106? android screen

最佳答案

坐标系正确。

getY()将返回顶部的值 View + Y 翻译。所以,如果getY()正在返回 106 并且您将翻译 y 设置为 10,您的 View 顶部应该在 96。也可以尝试调用 getTop()并检查那个值是多少

翻译是应用于 View 位置的偏移量.如果布局放置您的 Viewx;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/

相关文章:

android - 如何在 LG 智能电视上安装 Android 应用程序?

安卓 SQL DATETIME CURRENT_TIMESTAMP

c# - 切换任务时不会触发 Control.Enter 事件。有替代方案吗?

java - Android:当应用程序的多个屏幕具有相似布局时,避免代码重复的最佳方法是什么?

python - 如何在 Tkinter 中没有 "submit"按钮的情况下更新条目?

objective-c - NSTableColumn 大小以适合内容

Android NDK eabi - 如何让 ndk 知道使用 hard fp?

java - 你能在 Kotlin/Java 中强制编译器警告或错误吗?

java - 删除 ListView 项之间的间距

java - 如何解决选择组合框项目时出现错误