第九章 多語言環境的支援和多螢幕的適配(3)
9.3.4詳細說明Density
Density值,表示每英寸有多少個顯示點,它與螢幕解析度是兩個概念。HVGA屏density=160;QVGA屏density=120;WVGA屏density=240;WQVGA屏density=120。
apk的資源包中,當螢幕density=240時,使用hdpi標籤的資源;當螢幕density=160時,使用mdpi標籤的資源;當螢幕density=120時,使用ldpi標籤的資源。
不加任何標籤的資源,是各種解析度情況下共用的。
例如:我們有如下圖片資源:
res\drawable-nodpi --------------->logonodpi120.png (75x75) --------------->logonodpi160.png (100x100) --------------->logonodpi240.png (150x150) res\drawable-ldpi --------------->logo120dpi.png (75x75) res\drawable --------------->logo160dpi.png (100x100) res\drawable-hdpi --------------->logo240dpi.png (150x150) |
其中三種圖片資源的實際大小如圖9-1所示。
圖 9-1三種圖片資源的大小
執行以下示例程式碼:
//import publicclass DensityActivity extends Activity { @Override protectedvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setTitle(R.string.density_title); LinearLayoutroot = new LinearLayout(this); root.setOrientation(LinearLayout.VERTICAL); LinearLayoutlayout = new LinearLayout(this); layout= new LinearLayout(this); addResourceDrawable(layout,R.drawable.logo120dpi); addResourceDrawable(layout,R.drawable.logo160dpi); addResourceDrawable(layout,R.drawable.logo240dpi); addLabelToRoot(root,"dpi bitmap"); addChildToRoot(root,layout); layout= new LinearLayout(this); addResourceDrawable(layout,R.drawable.logonodpi120); addResourceDrawable(layout,R.drawable.logonodpi160); addResourceDrawable(layout,R.drawable.logonodpi240); addLabelToRoot(root,"No-dpi resource drawable"); addChildToRoot(root,layout); setContentView(root); } privatevoid addLabelToRoot(LinearLayout root, String text) { TextViewlabel = new TextView(this); label.setText(text); root.addView(label, newLinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); } privatevoid addChildToRoot(LinearLayout root, LinearLayout layout) { root.addView(layout, newLinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); } privatevoid addResourceDrawable(LinearLayout layout, int resource) { Viewview = new View(this); finalDrawable d = getResources().getDrawable(resource); view.setBackgroundDrawable(d); view.setLayoutParams( newLinearLayout.LayoutParams(d.getIntrinsicWidth(), d.getIntrinsicHeight())); layout.addView(view); } } |
執行以上程式碼,可以看到圖9-2的實際效果。
圖9-2程式執行的實際效果圖
經驗分享: 四種螢幕尺寸分類:small,normal,large,和xlarge。 四種密度分類:ldpi(low),mdpi(medium),hdpi(high),和xhdpi(extrahigh)。 需要注意的是:xhdpi是從Android2.2(APILevel 8)才開始增加的分類。 xlarge是從Android2.3 (APILevel 9)才開始增加的分類。 一般情況下的普通螢幕:ldpi是120,mdpi是160,hdpi是240,xhdpi是320。 |