Android中SP与DP区别的自我理解

来源:互联网 发布:阿里云 域名解析到网址 编辑:程序博客网 时间:2024/05/01 04:35

从一入Android开发的坑,就被告知这些常识
* 长度宽度的数值要使用dp作为单位放入dimens.xml文件中
* 字体大小的数值要使用sp作为单位放入dimens. xml文件中
然后,就没有然后了,约定俗成的就是这样,到底为什么这样,dp和sp有什么不同?
做个简单的Sample验证一下,一个简单的布局

 <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World! in SP"        android:textSize="18sp"/> <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World! in DP"        android:textSize="18dp"/>

得到的效果

然后进入系统设置中,更改字体大小

再次进入之前的界面,就会发现用sp作为字体大小单位,会随着系统的字体大小改变,而dp作为单位则不会

关于sp的API描述为:
Scale-independent Pixels – This is like the dp unit, but it is also scaled by the user’s font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user’s preference.
大致意思是
* sp除了受屏幕密度的影响外,还收到用户字体大小的影响
* 通常情况下,建议使用sp作为字体大小的单位。

0 0
原创粉丝点击