/** * 根據屏幕寬度設置高度值 */ private int getHeight() { //獲取屏幕寬度 DisplayMetrics dm = new DisplayMetrics(); double densityDpi = dm.density; //獲取屏幕信息 ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm); int screenWidth = dm.widthPixels; int height = (int) (screenWidth - 5 * densityDpi) / 6;//每一個圖片的寬度 return height; } //控件設置高度 android.view.ViewGroup.LayoutParams lp = holder.layout_items.getLayoutParams(); lp.height = getHeight();
1.使用的getHeight()與getWidth(),這種方法已經不推薦了java
2.使用getSize():android
private void getDisplayInfomation() { Point point = new Point(); getWindowManager().getDefaultDisplay().getSize(point); Log.d(TAG,"the screen size is "+point.toString()); }
3.使用getRealSize()佈局
private void getDisplayInfomation() { Point point = new Point(); getWindowManager().getDefaultDisplay().getSize(point); Log.d(TAG,"the screen size is "+point.toString()); getWindowManager().getDefaultDisplay().getRealSize(point); Log.d(TAG,"the screen real size is "+point.toString()); }
屏幕密度與DPI這個概念緊密相連,DPI全拼是dots-per-inch,即每英寸的點數。也就是說,密度越大,每英寸內容納的點數就越多。
android.util包下有個DisplayMetrics類能夠得到密度相關的信息。
最重要的是densityDpi這個成員,它有以下幾個經常使用值:spa
DENSITY_LOW = 120 DENSITY_MEDIUM = 160 //默認值 DENSITY_TV = 213 //TV專用 DENSITY_HIGH = 240 DENSITY_XHIGH = 320 DENSITY_400 = 400 DENSITY_XXHIGH = 480 DENSITY_XXXHIGH = 640
獲取方法:code
private void getDensity() { DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); Log.d(TAG,"Density is "+displayMetrics.density+" densityDpi is "+displayMetrics.densityDpi+" height: "+displayMetrics.heightPixels+ " width: "+displayMetrics.widthPixels); }
計算屏幕尺寸:圖片
首先求得對角線長,單位爲像素。
而後用其除以密度(densityDpi)就得出對角線的長度了。ip
densityDpi是每英寸的點數(dots-per-inch)是打印機經常使用單位(於是也被稱爲打印分辨率),而不是每英寸的像素數get
private void getScreenSizeOfDevice() { DisplayMetrics dm = getResources().getDisplayMetrics(); int width=dm.widthPixels; int height=dm.heightPixels; double x = Math.pow(width,2); double y = Math.pow(height,2); double diagonal = Math.sqrt(x+y); int dens=dm.densityDpi; double screenInches = diagonal/(double)dens; Log.d(TAG,"The screenInches "+screenInches); }
修改方法,引用PPI:it
private void getScreenSizeOfDevice2() { Point point = new Point(); getWindowManager().getDefaultDisplay().getRealSize(point); DisplayMetrics dm = getResources().getDisplayMetrics(); double x = Math.pow(point.x/ dm.xdpi, 2); double y = Math.pow(point.y / dm.ydpi, 2); double screenInches = Math.sqrt(x + y); Log.d(TAG, "Screen inches : " + screenInches); }
咱們在佈局文件中使用的dp/dip就是它。官方推薦使用dp是由於它會根據你設備的密度算出對應的像素。
公式爲:pixel = dip*density
須要注意的是,咱們在Java代碼中對控件設置寬高是不能夠設置單位的,而其自帶的單位是像素。因此若是動態修改控件大小時,
咱們的任務就來了,那就是將像素轉換爲dp。io
//pixel = dip*density; private int convertDpToPixel(int dp) { DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); return (int)(dp*displayMetrics.density); } private int convertPixelToDp(int pixel) { DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); return (int)(pixel/displayMetrics.density); }