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