一、背景
在用到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)?!原来,原来这几个坐标是相对于父容器来说的位置!