本文实例讲述了Android获取手机屏幕宽高、状态栏高度以及字符串宽高信息的方法。分享给大家供大家参考。具体如下:
首先定义TextView对象commentText
获取文字的宽高:
1
2
3
4
5
6
7
8
|
TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(commentText.getTextSize()); textPaint.setColor(Color.WHITE); FontMetrics fontMetrics = textPaint.getFontMetrics(); float fTop = fontMetrics.top; float fBottom = fontMetrics.bottom; float textHeight = ( int )(fBottom - fTop); float textWidth = ( int )textPaint.measureText(commentText.getText()); |
获取手机屏幕上方状态栏高度:
复制代码 代码如下:
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; //屏幕宽
int height = dm.heightPixels; //屏幕高
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top; //状态栏高
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight = contentTop - statusBarHeight; //标题栏高
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; //屏幕宽
int height = dm.heightPixels; //屏幕高
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top; //状态栏高
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight = contentTop - statusBarHeight; //标题栏高
获取手机屏幕宽高:
复制代码 代码如下:
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();//屏幕宽度
int height = wm.getDefaultDisplay().getHeight();//屏幕高度
int width = wm.getDefaultDisplay().getWidth();//屏幕宽度
int height = wm.getDefaultDisplay().getHeight();//屏幕高度
获取textView宽度
1
2
|
TextPaint paint = textView.getPaint(); float len = paint.measureText(string); |
获取屏幕尺寸:
1
2
3
4
5
|
DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); double x = Math.pow(dm.widthPixels/dm.xdpi, 2 ); double y = Math.pow(dm.heightPixels/dm.ydpi, 2 ); double screenInches = Math.sqrt(x+y); //屏幕尺寸(英寸) |
希望本文所述对大家的Android程序设计有所帮助。