Android之尺寸getDimension、getDimensionPixelOffset 和 getDimensionPixelSize

在Android Studio开发中,为规范代码,会建议开发者使用/res/values/dimens.xml的自定义尺寸。尽管eclipse编译可以通过,但以下代码仍提示报错:



好吧,我们先通过/res/values/dimens.xml自定义数值,了解一下尺寸(Dimension)不同用法:

<resources>  
    <dimen name="dp_value">16dp</dimen>  
    <dimen name="px_value">16px</dimen>  
    <dimen name="sp_value">16sp</dimen>  
</resources>  


执行结果:



再来看看文档描述:

public float getDimension
Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.


public int getDimensionPixelSize
Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This isthe same as getDimension, except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value(四舍五入), and ensuring that a non-zero base value is at least one pixel in size.


public int getDimensionPixelOffset
Retrieve a dimensional for a particular resource ID for use as an offset in raw pixels. This is the same as getDimension, except the returned value is converted to integer pixels for you. An offset conversion involves simply truncating the base value to an integer(忽略小数点部分).


结论:

相同点:返回获取某个dimen的值,如果dimen单位是dp或sp,则需要将其乘以density(屏幕密度);如果单位是px,则不用。

不同点:
getDimension:返回类型为float,
getDimensionPixelSize:返回类型为int,由浮点型转成整型时,采用四舍五入原则。 
getDimensionPixelOffset:返回类型为int,由浮点型转成整型时,原则是忽略小数点部分。

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android UI开发专题 Android UI开发专题(一) 之界面设计 近期很多网友对Android用户界面的设计表示很感兴趣,对于Android UI开发自绘控件和游戏制作而言掌握好绘图基础是必不可少的。本次专题分10节来讲述,有关OpenGL ES相关的可能将放到以后再透露。本次主要涉及以下四个包的相关内容:  android.content.res 资源类   android.graphics 底层图形类   android.view 显示类   android.widget 控件类   一、android.content.res.Resources   对于Android平台的资源类android.content.res.Resources可能很多网友比较陌生,一起来看看SDK上是怎么介绍的吧,Contains classes for accessing application resources, such as raw asset files, colors, drawables, media or other other files in the package, plus important device configuration details (orientation, input types, etc.) that affect how the application may behave.平时用到的二进制源文件raw、颜色colors、图形drawables和多媒体文件media的相关资源均通过该类来管理。   int getColor(int id) 对应res/values/colors.xml   Drawable getDrawable(int id) 对应res/drawable/   XmlResourceParser getLayout(int id) 对应res/layout/   String getString(int id) 和CharSequence getText(int id) 对应res/values/strings.xml   InputStream openRawResource(int id) 对应res/raw/   void parseBundleExtra (String tagName, AttributeSet attrs, Bundle outBundle) 对应res/xml/   String[] getStringArray(int id) res/values/arrays.xml   float getDimension(int id) res/values/dimens.xml

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值