遇到的问题
- 抽屉里的headview背景图片在手机里正常,而跑在平板里就变得非常扁
解决方法
先说第一种方法,这种方法只会获得屏幕分辨率,而Android平板的分辨率有可能比配置高的Android智能机分辨率还低,我手机分辨率是,而公司分配的平板分辨率是800*1280,所以没有
navView.inflateHeaderView(R.layout.nav_header_main);
WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
View headerView = navView.getHeaderView(0);
mLayoutOfHeader = headerView.findViewById(R.id.ll_header_bg);
if (width>790 && height >1100){
heightOfHeader = (int) getResources().getDimension(R.dimen.header_height);
Log.d("MainActivity", "heightOfHeader:" + heightOfHeader);
mLayoutOfHeader.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,heightOfHeader));
}
第二种有用的方法–自己根据分辨率,屏幕DPI(dots-per-inch(每英寸的点数))计算设备的物理英寸大小
先看结果
Log.d("abc", x + "\n" + y + "\n" + diagonal + "\n" + dens + "\n");
Log.d("abc","The screenInches "+screenInches);
首先是平板测试结果
输出日志为
07-25 09:18:32.532 32128-32128/? D/abc: 640000.0
1478656.0
1455.5603731896524
213
07-25 09:18:32.532 32128-32128/? D/abc: The screenInches 6.833616775538275
屏幕大小大约为6.8
再看看我手机的测试结果
输出日志
07-25 09:35:27.193 22155-22155/com.example.administrator.hlfrobot D/abc: 1166400.0
3686400.0
2202.9071700822983
480
07-25 09:35:27.193 22155-22155/com.example.administrator.hlfrobot D/abc: The screenInches 4.589389937671455
屏幕大小为4.6
只要判断出物理屏幕的大小就可以愉快的判断来动态设置具体的宽高了。
现在贴一下代码
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
double x = Math.pow(width,2);
double y = Math.pow(height,2);
double diagonal = Math.sqrt(x + y);
int dens = displayMetrics.densityDpi;
double screenInches = diagonal/(double)dens;
Log.d("abc", x + "\n" + y + "\n" + diagonal + "\n" + dens + "\n");
Log.d("abc","The screenInches "+screenInches);