View的位置--top, left, bottom, right

一、背景

在用到view的位置时,查到的API有一大堆,什么 getTop()getTranslationX(), getX(),不知道这些位置具体代表的是什么东西。于是今天就先研究下top, left, bottom, right这几个坐标。

二、坐标

Android的坐标系的x轴向下是正方向,y轴向右是正方向。top, left, bottom, right这几个属性是View类就具有的,顾名思义就是一个view的左上角的坐标和右下角的坐标。但是这个坐标是相对于谁的?是相对于屏幕左上角?还是相对于父容器?还是相对于其他?

三、代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/block1"
        android:layout_width="match_parent"
        android:layout_height="200px"
        android:background="@color/blue"/>

    <RelativeLayout
        android:id="@+id/block2"
        android:layout_below="@+id/block1"
        android:layout_width="match_parent"
        android:layout_height="2000px"
        android:background="@color/red">

        <Button
            android:id="@+id/button"
            android:layout_width="250px"
            android:layout_height="100px"
            android:layout_marginLeft="30px"
            android:layout_marginTop="30px"
            android:text="button"/>
    </RelativeLayout>
</RelativeLayout>

(当然用px在xml里是绝对不推荐,但是为了这次log能够看的清楚写的测试程序)
那么打出log看一看这几个控件的实际位置:

button, top:30,left:30:bottom:130,right:280
block1, top:0,left:0:bottom:200,right:720
block2, top:200,left:0:bottom:1118,right:720

四、结论

button的左上角位置居然是(30,30)?!原来,原来这几个坐标是相对于父容器来说的位置!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值