在實際應用中,爲了適配屏幕,要知道所用的手機的分辨率。
本篇文章借鑑於http://blog.csdn.net/lincyang/article/details/42679589
並應用於實際項目中,得到了很大的幫助,感謝該博主的分享
1.獲取分辨率
Android 早期的版本可以通過getHeight(),getWidth()獲取屏幕寬高,現在已經不推薦使用了
現在獲取分辨率的可使用getSize();//方法的原型可參考API
public void getDisplayInfo(){
Point point = new Point();
getWindowManager().getDefaultDisplay().getSize(point);
Log.e("TAG","==屏幕分辨率=="+point.toString());
//getWindowManager().getDefaultDisplay().getRealSize(point);
//Log.e("TAG","==屏幕分辨率=="+point.toString());
}
另外,Android還提供了一種方法getRealSize();
這兩種方法有一定的區別:通常情況下兩者的返回值並無差別
但是,在Androidmanifest.xml設置不同的主題後,兩者會有差別
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
Activity繼承ActionBarActivity
>注:這種方式也有可能不會有差別,讀者可參考以上分享博文
2、屏幕密度
屏幕密度:DPI <dots-per-inch> 每英寸的點數,密度越大,每英寸容納的點數就越多
public void getDensity(){
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
Log.e("TAG",Density is "+displayMetrics.density+
"densityDpi is "+displayMetrics.densityDpi +"height:"+displayMetrics.heightPixels
+"width: "+displayMetrics.widthPixels );
}
3、屏幕尺寸
屏幕尺寸:對角線長度,單位:英寸,1英寸=2.54釐米
public void getScreenSizeOfDevice(){
Point point = new Point();
getWindowManager().getDefaultDisplay().getRealSize(point);
DisplayMetrics dm = getResources().getDisplayMerics();
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);
}
4、DIP即dp,與密度無關的像素,現在常在佈局文件中使用
官方推薦使用dp是因爲它會根據你設備的密度算出相應的像素值,px = dp*density;
>注意:在Java代碼中對控件設置寬高是不可以設置單位的,其自帶的單位是像素,如果需要動態修改控件大小時,就要實現px 與dp之間的轉換
代碼:
//px = dp*density
public int dpTopx(int dp){
DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
return (int)(dp*displayMetrics.density);
}
public int pxTodp(int px){
DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
return (int)(px/displayMetrics.density);
}