获取控件在屏幕中的坐标
来源:互联网 发布:数据结构与算法 树 编辑:程序博客网 时间:2024/05/17 06:55
1.核心函数
getLocationOnScreen //获取在当前屏幕内的绝对坐标 (注意这个值是要从屏幕顶端算起,包括了状态栏和通知栏的高度)getLocationInWindow //获取在整个窗口内的绝对坐标,感觉安卓里面没有窗口的概念,测了几组数据和上边函数效果类似getLeft , getTop, getBottom, getRight, 这一组是获取相对在它父亲里的坐标
2.核心代码
int[] location = new int[2] ;view.getLocationInWindow(location); //获取在当前窗口内的绝对坐标view.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标location [0]--->x坐标,location [1]--->y坐标
3.自己写的例子
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btn" android:layout_width="200dp" android:layout_height="100dp" android:text="按钮"/> <Button android:id="@+id/btn1" android:layout_marginTop="80dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮"/></LinearLayout>activity代码
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getButtonLocation(); } public void getButtonLocation() { final Button btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int[] position = new int[2]; //btn.getLocationInWindow (position);//相对于窗口的坐标 btn.getLocationOnScreen (position);//相对于屏幕的坐标 Toast.makeText(getApplicationContext(),"距离左边屏幕距离:"+position[0]+"距离上边屏幕距离:"+position[1],Toast.LENGTH_SHORT).show(); } }); final Button btn1 = (Button) findViewById(R.id.btn1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int[] position = new int[2]; btn1.getLocationOnScreen (position);//相对于屏幕的坐标 Toast.makeText(getApplicationContext(),"距离左边屏幕距离:"+position[0]+"距离上边屏幕距离:"+position[1],Toast.LENGTH_SHORT).show(); } }); }}
运行结果:(我在电视机上测的,没有状态栏和标题栏)
距离左边屏幕距离:0 距离上边屏幕距离:0距离左边屏幕距离:0 距离上边屏幕距离:180
0 0
- 获取控件在屏幕中的坐标
- Android 获取某控件在屏幕中的位置/坐标
- android 获取控件在屏幕中的位置(坐标)
- 获取View控件在屏幕的坐标
- Winfrom 获取控件在屏幕的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android 得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- Android得到控件在屏幕中的坐标
- 获取View在屏幕中的坐标
- phpStudy启动错误之Apache无法启动
- 数星星
- android对象序列化
- Android RelativeLayout padding 的一个坑?
- Flask开发碰到的socket.error: [Errno 10053]
- 获取控件在屏幕中的坐标
- Android之RecyclerView——用ItemDecoration装饰你的Item
- CentOS 7设置NTP、SSH服务
- python学习笔记 条件判断和循环
- Django Templates的设置
- 解决Cannot change version of project facet Dynamic web module to 2.5
- 代码中的注释FIXME/TODO/XXX
- 粗略web开发简史,开发步骤与原理
- MATLAB(R2012b)生成64位的.NET Assembly dll