getLocationOnScreen
,计算该视图在全局坐标系中的x,y值,(注意这个值是要从屏幕顶端算起,也就是索包括了通知栏的高度)//获取在当前屏幕内的绝对坐标
getLocationInWindow
,计算该视图在它所在的widnow的坐标x,y值,//获取在整个窗口内的绝对坐标 (不是很理解= =、)
getLeft
,
getTop
,
getBottom
,
getRight
,
这一组是获取相对在它父亲里的坐标
getLocationInWindow
getLeft
如果在Activity的OnCreate()事件输出那些参数,是全为0,要等UI控件都加载完了才能获取到这些。
附上部分代码:获取Button在整个屏幕窗口内的位置
int[] location = new int[2];
button.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
Log.e("位置", "X轴坐标:"+x+"Y轴坐标:"+y);<pre name="code" class="html">System.out.println("button的各个角的坐标Left:"+button.getLeft()+"Right:"+<span style="font-family: Verdana, Arial, Helvetica, sans-serif;">button</span><span style="font-family: Verdana, Arial, Helvetica, sans-serif;">.getRight()+"Top:"+button.getTop()+"Bottom:"+button.getBottom()); </span>
同时附上自定义PopupWindow 显示在点击的控件正上方的主要代码:
public class MainActivity extends Activity {
private PopupWindow popupWindow;
private Button button01;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
popupWindow = new PopupWindow(LayoutInflater.from(this).inflate(R.layout.popupwindow, null), 200, 200);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
//popupWindow.setAnimationStyle(R.style.popupwindow);
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher));
//假如设置了 setBackgroundDrawable 就算没有设置 .setoutsideTouchable 也可以点击popupwindow之外的地方使popupwindow消失
//只设置了 setfocusable 而没设置 setbackgroundDrawable 点击Popupwindow 之外的地方 popupwindow不消失
button01 = (Button) findViewById(R.id.button01);
//Button button02 = (Button) findViewById(R.id.button02);
button01.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int[] location = new int[2];
button01.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
Log.e("位置", "X位置:"+x+"Y位置:"+y);
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, x, y-popupWindow.getHeight());
}
});
}