Configuration类的常量与变量
屏幕大小判断
Configuration类用于描述手机设备上的配置信息
1 2
| Configuration configuration = getResources().getConfiguration();
|
通过Configuration对象就可以获取系统的配置信息,例如
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
| int a = this.getResources().getConfiguration().screenLayout;
int b = Configuration.SCREENLAYOUT_SIZE_MASK;
int c = a & b;
int d = Configuration.SCREENLAYOUT_SIZE_LARGE
int d = Configuration.SCREENLAYOUT_SIZE_NORMAL
int d = Configuration.SCREENLAYOUT_SIZE_SMALL
int d = Configuration.SCREENLAYOUT_SIZE_UNDEFINED
int d = Configuration.SCREENLAYOUT_SIZE_XLARGE
boolean e = c > d;
|
判断是否为平板
官方给的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| private boolean isPad(Context context){
int a = context.getResources().getConfiguration().screenLayout;
int b = Configuration.SCREENLAYOUT_SIZE_MASK;
int c = a & b;
int d = Configuration.SCREENLAYOUT_SIZE_LARGE;
boolean e = c > d;
return e; }
|
简化合并一下
1 2 3
| private boolean isPad(Context context){ return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; }
|
总起来说,就是获取屏幕bit大小,然后通过SCREENLAYOUT_SIZE_MASK计算当前bit大小的代表值,通过代表值的对比,就可以得到当前屏幕至少应该有多大
但是这种方法在一定环境的刺激下就不灵了,比如华为的平板可以放大界面,所以有了一种优化方案:
获取屏幕的长度和宽度(单位像素),通过计算屏幕的对角线长度,用对角线像素值计算出英寸大小,目前市面上最小的平板是7.0英寸,如果我们计算的英寸值大于等于7.0,说明当前的设备是平板设备,反之则是手机设备
1 2 3 4 5 6 7 8 9 10 11 12
| private boolean isPad(Context context){ WindowManager windowManager = (WindowManager) context.getSystemService(context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics displayMetrics = new DisplayMetrics(); display.getMetrics(displayMetrics); double x = Math.pow(displayMetrics.widthPixels / displayMetrics.xdpi, 2); double y = Math.pow(displayMetrics.heightPixels / displayMetrics.ydpi, 2);
double inch = Math.sqrt(x + y);
return inch >= 7.0; }
|