Android 获取View的 left、right、top、buttom、以及x、y坐标的方法

xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
        <Button
            android:id="@+id/id_scale_btn"
            android:layout_width="150px"
            android:layout_height="100px"
            android:layout_y="400px"
            android:text="scalse"
            android:textSize="40px" 

        <AbsoluteLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="180px"
            android:layout_y="400px" >

            <Button
                android:id="@+id/id_change_layout"
                android:layout_width="200px"
                android:layout_height="150px"
                android:text="change layout"
                android:layout_x="20px"
                android:textSize="40px" />
        </AbsoluteLayout>
</AbsoluteLayout>

一、View.getLeft()、getRight()、getTop()、getBottom
注意:getLeft()、getRight()、getTop()、getBottom 获取的值是相对于父布局的
所以上面的Button 的getLeft() = 0、getRight() = 150、getTop() = 400 、getBottom = 550。
下面的button的getleft() = 20,因为相对于他的父布局为20px (android:layout_x=”20px).
getRight = 20+200 ;
getTop = 0;()
getButtom = 0+150 ;

二、View.getLocationOnScreen(location)
计算该视图在全局坐标系中的x,y值,(注意这个值是要从屏幕顶端算起,也就是索包括了通知栏的高度,除非在MainActivity中调用requestWindowFeature(Window.FEATURE_NO_TITLE)来取消标题栏)
其中 location = new int [2];
int x = location[0];
int y = location[1];

1.当调用requestWindowFeature(Window.FEATURE_NO_TITLE)来取消标题栏
上面的Button 的 x = 0; y = 400
下面的 Button 的 x = 180 +20;(表示相对于屏幕左边缘的位置)
y = 400;

当没调用requestWindowFeature(Window.FEATURE_NO_TITLE)来取消标题栏则 y的值会大于400,
因为此时 要加上标题栏的高度

三、方法如下:
ViewGroup vg = ((ViewGroup)getWindow().getDecorView());
Rect mRect = new Rect();
mButton2.getFocusedRect(mRect);
vg.offsetDescendantRectToMyCoords(mButton2, mRect);//获取view 的Rect(距离屏幕的)
Log.e(“ccc”, “left = “+mRect.left+” , right = “+mRect.right+”, top = “+mRect.top+”, bottom = “+mRect.bottom);

获取的也是相对于屏幕的值。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值