第九章 多语言环境的支持和多屏幕的适配(3)

9.3.4详细说明Density

Density值,表示每英寸有多少个显示点,它与屏幕分辨率是两个概念。HVGAdensity=160QVGAdensity=120WVGAdensity=240WQVGAdensity=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所示。

第九章 多语言环境的支持和多屏幕的适配(3)_第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的实际效果。

第九章 多语言环境的支持和多屏幕的适配(3)_第2张图片

9-2程序运行的实际效果图


经验分享:

四种屏幕尺寸分类:smallnormallarge,和xlarge

四种密度分类:ldpilow),mdpimedium),hdpihigh),和xhdpiextrahigh)。

需要注意的是:xhdpi是从Android2.2APILevel 8)才开始增加的分类。

xlarge是从Android2.3 APILevel 9)才开始增加的分类。

一般情况下的普通屏幕:ldpi120mdpi160hdpi240xhdpi320


你可能感兴趣的:(*07,Android,《Android应用开发精解》)