您的位置:首页 > 移动开发 > Android开发

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

2016-07-28 19:12 555 查看
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);

获取的也是相对于屏幕的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息