標籤:
1、在xml布局檔案中,控制項的寬度和高度用 dp ; 字型大小用 sp
2、根據螢幕的寬高來動態適配 , 擷取螢幕的寬高的兩種方法:
第一種方法:
/** * 螢幕的寬度 * 螢幕的高度 * @return */ public void initPhone1( Activity activity ){ int phone_Width = activity.getWindowManager().getDefaultDisplay().getWidth() ; //單位是 px int phone_Height = activity.getWindowManager().getDefaultDisplay().getHeight() ; //單位是 px }
這種方法會警示告,The method getWidth() from the type Display is deprecated
意思是這種方法已經過時,所有建議用第二種方法:
第二種方法:
DisplayMetrics dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);int Phone_width = dm.widthPixels ;
int Phone_height = dm.heightPixels ;
注意:1、在 Java 代碼中擷取的寬度和高度,以 px (像素) 為單位。 與xml 檔案中的 dp 不一樣 。
2、經過測試,用兩種方法分別擷取手機螢幕的寬度和高度,得到的結果是一樣的 。
My Phone是小米1 ,480 x 854 px
3、通常情況下,一個 layout 布局檔案裡面的控制項的大小,有兩種設定控制項寬高的 方法 。
一種是在 xml 中設定 , 如果一個控制項在 xml 中有定義,控制項的寬度和高度用 dp ; 字型大小用 sp 。
另外一種 就是在java 代碼中動態設定 。
TextView tv2 = (TextView) findViewById( R.id.tv2 ) ; LinearLayout.LayoutParams params2 = (LayoutParams) tv2.getLayoutParams() ; params2.width = 300 ; //這裡的300代表 300 px params2.height = 100 ; //這裡的100代表 100 px tv2.setLayoutParams( params2 );
4、因為在 xml 布局中 單位是 dp , 在 java 代碼中 的單位是 px 。
為了兩者的大小保持一致,所以需要將兩者進行換算 。
DensityUtil 類
package com.example.bb;import android.content.Context;public class DensityUtil { /** * 根據手機的解析度從 dp 的單位 轉成為 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根據手機的解析度從 px(像素) 的單位 轉成為 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
4、由於android 的螢幕大小有很多中,解析度也是多種多樣的 。
為了準確的擷取螢幕的高度和寬度,需要在AndroidManifest.xml 中加入 supports-screens 節點 。
?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app01" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <!-- 獲得手機正確的寬度和高度 --> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.app01.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
android 多螢幕適配 : 第一部分