Android在自定义控件时,经常需要获得屏幕的宽高,每次都要写,不妨直接把他封装成工具类,直接拿来用,废话不说,直接上代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
/** * */ package com.example.customview; import android.content.Context; import android.util.DisplayMetrics; import android.view.WindowManager; /** * 获取手机屏幕大小 * @author * */ public class MeasureUtil { /** * 宽 * @return */ public static int getWidth(Context context){ WindowManager wm=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); return outMetrics.widthPixels; } /** * 高 * @return */ public static int getHeight(Context context){ WindowManager wm=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); return outMetrics.heightPixels; } } |