如何在XML中为整数值添加单位?Android资源配置语法问题
你出现编译错误的核心原因是Android中带单位的边距、字号等尺寸类数值,不能用integer类型资源定义,需要使用专属的dimen(尺寸)资源类型。
正确实现步骤
1. 修改资源文件定义
在values目录下创建/修改dimens.xml(也可以放在原有资源文件中,开发规范建议单独存放尺寸资源),把原来的integer定义替换为dimen定义,直接在数值后标注对应单位:
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- 边距类属性用dp单位 --> <dimen name="margin_bottom">5dp</dimen> <!-- 字号类属性用sp单位 --> <dimen name="text_size">50sp</dimen> </resources>
2. 修改布局中TextView的资源引用
把原来引用@integer的部分替换为@dimen即可:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginBottom="@dimen/margin_bottom" android:textSize="@dimen/text_size" android:textAppearance="@android:style/TextAppearance.Large" android:layout_centerHorizontal="true" android:text="Hello World" android:id="@+id/txtNew"/>
补充说明
如果需要在业务代码中动态获取这些尺寸值,可以通过以下方式获取已经换算完成的像素值,直接传给控件对应参数即可:
- Kotlin代码:
val marginBottom = resources.getDimensionPixelSize(R.dimen.margin_bottom) - Java代码:
int marginBottom = getResources().getDimensionPixelSize(R.dimen.margin_bottom);
内容的提问来源于stack exchange,提问作者randofan
相关产品推荐
相关产品推荐

