转载----android应用程序中获取view的位置
来源:互联网 发布:网络销售法律法规 编辑:程序博客网 时间:2024/05/22 06:03
获取View类界面控件的位置,有助于添加新的控件。
- 获取在parent里的相对坐标位置
这个比较简单,不用多说,直接调用View的方法:getLeft , getTop, getBottom, getRight 获得。
- 获取在屏幕中的绝对位置
- getLocalVisibleRect
- getGlobalVisibleRect
- getLocationOnScreen
- getLocationInWindow
有一遍写得不错的文章,转帖如下:(原文地址:http://www.fengfly.com/plus/view-209439-1.html)
=======================================================================
我们重点在获取view的y坐标,你懂的...
依次介绍以下四个方法:
1.getLocationInWindow
int[] position = new int[2];
textview.getLocationInWindow(position);
System.out.println("getLocationInWindow:" + position[0] + "," + position[1]);
这个方法是将view的左上角坐标存入数组中.此坐标是相对当前activity而言.
若是普通activity,则y坐标为可见的状态栏高度+可见的标题栏高度+view左上角到标题栏底部的距离.
可见的意思是:在隐藏了状态栏/标题栏的情况下,它们的高度以0计算.
若是对话框式的activity,则y坐标为可见的标题栏高度+view到标题栏底部的距离.
此时是无视状态栏的有无的.
2.getLocationOnScreen
int[] position = new int[2];
textview.getLocationOnScreen(position);
System.out.println("getLocationOnScreen:" + position[0] + "," + position[1]);
这个方法跟上面的差不多,也是将view的左上角坐标存入数组中.但此坐标是相对整个屏幕而言.
y坐标为view左上角到屏幕顶部的距离.
3.getGlobalVisibleRect
Rect viewRect = new Rect();
textview.getGlobalVisibleRect(viewRect);
System.out.println(viewRect);
这个方法是构建一个Rect用来"套"这个view.此Rect的坐标是相对当前activity而言.
若是普通activity,则Rect的top为可见的状态栏高度+可见的标题栏高度+Rect左上角到标题栏底部的距离.
若是对话框式的activity,则y坐标为Rect的top为可见的标题栏高度+Rect左上角到标题栏底部的距离.
此时是无视状态栏的有无的.
4.getLocalVisibleRect
Rect globeRect = new Rect();
button.getLocalVisibleRect(globeRect);
注意:
以上方法在OnCreate方法中调用,都会返回0,这是因为View还未加载完毕.
建议在onWindowFocusChanged方法中进行获取,有些情况下onWindowFocusChanged不好用的时候(比如ActivityGroup),可以这样写:
mTextView.post(new Runnable() {
@Override
public void run() {
Rect viewRect = new Rect();
mTextView.getLocalVisibleRect(viewRect);
mTreeScrollView.setRect(viewRect);
}
});
这样在View加载完毕之后会执行获取位置的方法.
=======================================================================
PS:如何动态创建一个View类控件:
1、通过new方法来创建一个界面对象;
2、通过Layout xml资源来创建,利用LayoutInflater提供的方法。
- 转载----android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- Android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- android应用程序中获取view的位置
- 坐标相关的android应用程序中获取view的位置
- android应用程序中获取view的位置(2)
- Android tips(四)-->Android应用程序中获取view的位置
- 使用 resizableImageWithCapInsets获得想要的图片
- linux学习笔记--基本命令的学习--压缩与解压缩命令
- leetcode-21 Merge Two Sorted Lists
- AC自动机模板
- ARP地址解析协议与RAPR逆地址解析协议
- 转载----android应用程序中获取view的位置
- Visual Studio 2005/2008中如何编译和运行C++程序
- vim+cscope+ctags打造属于自己的IDE
- 关于算法练习1.1中的中参数传递方式思考
- 如何用堆栈实现后序遍历的非递归程序
- Sizeof与Strlen的区别与联系
- uint8_t / uint16_t / uint32_t /uint64_t 是什么数据类型 - 大总结,看完全明白了
- c++读取word文件
- 利用textField的代理和手势来进行取消第一响应的事件来提高用户体验!