Android之尺寸getDimension、getDimensionPixelOffset 和 getDimensionPixelSize

本文深入解析了Android开发中尺寸资源的使用方法,包括dimens.xml文件的定义方式及getDimension、getDimensionPixelSize与getDimensionPixelOffset三个方法的区别。通过实例展示了如何根据不同场景选择合适的尺寸获取方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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,由浮点型转成整型时,原则是忽略小数点部分。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值