android获取屏幕尺寸,标题栏,状态栏高度,控件位置坐标

时间:2021-09-18 10:53:19


 1.屏幕尺寸,源代码如下:

DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
     int screenWidth=metrics.widthPixels;            //屏幕宽度
     int .screenHeight=metrics.heightPixels;        //屏幕高度

2.获取标题栏、状态栏高度:

Rect rect = new Rect(); 
     Window win = this.getWindow(); 
     win.getDecorView().getWindowVisibleDisplayFrame(rect); 
     int statusBarHeight = rect.top; //状态栏高度
     int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop(); 
     int titleBarHeight = contentViewTop - Variable.statusBarHeight;    //标题栏高度

部分手机contentViewTop 获取到的数据会为0,特此标注
3.控件坐标位置:

       //getLeft , getTop, getBottom, getRight, 这一组是获取相对在它父亲里的坐标
int[] location = new  int[2] ;
view.getLocationInWindow(location); //获取在当前窗口内的绝对坐标
view.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标
//location [0]:x坐标,location [1]:y坐标