关于自定义控件和属性时TypedArray.getDimension应当注意的问题
关于自定义控件以及自定义属性的文章,可以查看 Android高手进阶教程(四)之----Android 中自定义属性(attr.xml,TypedArray)的使用!。本文主要在其基础之上结合实际开发当中遇到的问题,举例分析一下在使用TypedArray.getDimension时应当注意的问题。
一、主要代码以及不同手机显示图片主要显示代码main.xml关键代码:
中兴 v880
中兴 n760
华为c8500
二、现象说明
我们看到根据屏幕大小的不同,两行文字中下行文字的大小也随之改变,其中摩托罗拉xt910和中兴 v880下面字体的都比上面字体大,而中兴 n760下面字体与上面字体大小是相同的,而华为c8500下面字体比上面字体小。我们再来看看main.xml代码:
public float getDimension (int id)Since: API Level 1Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current
DisplayMetricsassociated with the resources.Parameters
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.Returns
- Resource dimension value multiplied by the appropriate metric.
Throws
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.See Also
getDimensionPixelOffset(int)getDimensionPixelSize(int)Unit conversions are based on the current DisplayMetrics associated with the resources.单位的转换是基于当前资源显示分比率的。
因此我们要慎重使用getDimension定义的属性,不然我们的应用部署到不同的应用上,原先非常美丽的效果,会变得面目全非。
四、解决方案使用时,默认将字体大小设定好,而在xml配置文件当中删除关于字体大小的设置。如
删除main.xml
float contentSize = typeArray.getDimension(R.styleable.TextViewAndSpaner_item_content_textsize, 15);


