android view getLeft(), getRight(), getTop(), getBottom()等相对位置 与getGlobalVisibleRect(Rect r)等绝对位置

本文详细介绍了Android中View的getTop(), getBottom(), getLeft(), getRight()等方法的功能,用于获取View在其父容器中的相对位置。同时,文中也解释了getWidth(), getHeight(), getMeasuredWidth()的区别,并提供了获取View绝对位置的方法。


View的getTop()getBottom()getLeft()getRight()获取的都是当前View相对于它的父类容器的顶部、底部、左边和右边的位置是相对位置

看下图:




   right = left + width;

   bottom = top + height;

再来看一看getHeight(),getWidth(),他们是这样的



总结(正解):
 getWidth()/getHeight: View在设定好布局后整个View的宽度/高度。
 getMeasuredWidth(): 对View上的内容进行测量后得到的View内容佔据的宽度,前提是你必须在父布局的onLayout()方法或者此View的onDraw()方法裡调 用measure(0,0);(measure 参数的值你可以自己定义),否则你得到的结果和getWidth()得到的结果一样。





那如何获取View的绝对位置呢?

http://www.cnblogs.com/mengdd/p/3273284.html

getGlobalVisibleRect(Rect r)是可以得到绝对坐标的。



getLocationInWindow(int[] location) 返回View左上角的绝对坐标


getLocationOnScreen(int[] location) 返回View左上角的绝对坐标

这两个方法目前还不出有什么差别。

直接看代码 




    private String getViewInfo(View view) {
        StringBuffer stringBuffer = new StringBuffer();


        int top = view.getTop();
        int left = view.getLeft();
        int right = view.getRight();
        int bottom = view.getBottom();
        int width = view.getWidth();
        int height = view.getHeight();


        stringBuffer.append("Info relative to Parent: " + "left: " + left
                + ", right: " + right + ", top: " + top + ", bottom: " + bottom
                + ", width: " + width + ", height: " + height);


        // API Level 11
        stringBuffer.append("\n view.getTranslationX(): "
                + view.getTranslationX());
        stringBuffer.append("\n view.getTranslationY(): "
                + view.getTranslationY());


        Rect rect = new Rect();
        view.getLocalVisibleRect(rect);
        stringBuffer.append("\ngetLocalVisibleRect(): ");
        stringBuffer.append("\n " + rect.toString());


        Rect globalRect = new Rect();
        view.getGlobalVisibleRect(globalRect);
        stringBuffer.append("\ngetGlobalVisibleRect(): ");
        stringBuffer.append("\n " + globalRect.toString());


        int[] locationInWindow = new int[2];
        view.getLocationInWindow(locationInWindow);
        stringBuffer.append("\ngetLocationInWindow(): ");
        stringBuffer.append("\n " + locationInWindow[0] + ", "
                + locationInWindow[1]);


        int[] locationOnScreen = new int[2];
        view.getLocationOnScreen(locationOnScreen);
        stringBuffer.append("\ngetLocationOnScreen(): ");
        stringBuffer.append("\n " + locationOnScreen[0] + ", "
                + locationOnScreen[1]);


        return stringBuffer.toString();
   


}















评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Android西红柿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值