最近遇到非常多需要获取控件在屏幕中位置的需求,用途有很多,比如一些抛物线动画的起始点、popupwindow的显示位置、scrollview中用于滑动跳转到固定位置等,这里总结一下:
1.获取屏幕的大小
WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
int width = manager.getDefaultDisplay().getWidth();
int heigh = manager.getDefaultDisplay().getHeight();
//第二种
WindowManager manager1 = this.getWindowManager();
int width1 = manager1.getDefaultDisplay().getWidth();
int heigh1 = manager1.getDefaultDisplay().getHeight();
//第三种
WindowManager manager2 = this.getWindowManager();
DisplayMetrics outMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(outMetrics);
int width3 = outMetrics.widthPixels;
int height3 = outMetrics.heightPixels;
//第四种
Resources resources = this.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
float density = dm.density;
int width4 = dm.widthPixels;
int height4 = dm.heightPixels;
日志输出:
其中方法一和二过时了,建议使用后两个,density 为屏幕密度。
2.获取控件的位置
int[] location = new int[2];
v.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
//第二种
int[] location1 = new int[2];
v.getLocationInWindow(location1);
int x1 = location[0];
int y1 = location[1];
getLocationOnScreen获取在整个屏幕内的绝对坐标,注意这个值是要从屏幕顶端算起,也就是包括了通知栏的高度。getLocationInWindow获取在当前窗口内的绝对坐标.
getLocationInWindow()和 getLocationOnScreen()在window占据全部screen时,返回值相同,不同的典型情况是在Dialog中时。当Dialog出现在屏幕中间时,View.getLocationOnScreen()取得的值要比View.getLocationInWindow()取得的值要大。
这里需要注意的是:如果在oncreate中去获取控价的位置得到的都是0,原因是因为此时控件还没有加载完。
3.获取控件的宽高
控件宽高有view.getWidth()和view.getHeight(),但是这两个方法在onCreate()方法里同样得到的都是0,先找到几种方式:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.i("apple",begin.getWidth()+"~~onWindowFocusChanged~~"+begin.getHeight());
}
begin.post(new Runnable() {
@Override
public void run() {
int[] location = new int[2];
begin.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
Log.i("apple","by onCreate x~~~"+x+"~~~y~~~"+y);
Log.i("apple",begin.getWidth()+"~~post~~"+begin.getHeight());
}
});
int w = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
begin.measure(w, h);
int btwidth = begin.getMeasuredWidth();
int btheight = begin.getMeasuredHeight();
Log.i("apple","btwidth~~~"+btwidth+"~~~btheight~~~"+btheight);
第一种重写onWindowFocusChanged方法,第二三种都是可以在oncreate里获取到宽高的。