获取控件在屏幕中的坐标

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


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值