在Android开发中,常用的尺寸单位有 dp , px , sp 。当然还有其他的单位如 pt , mm 等,不过这些都是不常用,所以我们重点来探究一下 dp , px , sp 这三个常用的单位。
- px
英文pixel的缩写,即像素。无论屏幕密度为多少,一个像素单位对应屏幕上的一个像素,因此在android开发中并不推荐使用px为单位,因为它在不同分辨率的屏幕上显示的效果差别很大。 - dp(或dip)
英文density-independent pixel的缩写,意思为密度无关像素,可以把它理解为一个物理尺寸,即不管在什么分变率的屏幕上表现出的大小都是一致的,所以在设定视图尺寸的时候,推荐以dp座位视图的单位。 - sp 英文
scale-independent pixel的缩写,意思是与缩放无关的像素。它也是一种与密度无关的像素。通常使用sp作为字体大小的单位。
了解了这三种的单位的不同,我们来看看在实际应用中它们的效果:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="Text size is 30px"
android:textSize="30px"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="Text size is 30dp"
android:textSize="30dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="Text size is 30sp"
android:textSize="30sp"/>
</LinearLayout>
在上面的代码中我们定义了三个分别使用不同单位的 TextView ,我们来看看在不同分辨率下它们的表现如何:
由上图可见, 以 dp 为单位的字体,无论在什么情况下表现的大小都相同,以 px 为单位的字体在不同分辨率下表现的大小不同,在高分辨率的屏幕上表现的更小一些,在低分辨率的屏幕上表现的更大一些。以 sp 为单位的字体只会随系统设置中字体的大小做一定的改变,而与屏幕的分辨率也没有关系。
希望可以帮到对尺寸的单位有疑惑的朋友。
本文介绍了Android开发中常用的尺寸单位dp、px和sp的区别,并通过实例展示了它们在不同分辨率屏幕上的表现效果。
—— 屏幕尺寸单位dp,px,sp的探究&spm=1001.2101.3001.5002&articleId=79320728&d=1&t=3&u=d7c3879325a449fb9100d91e65746755)
1297

被折叠的 条评论
为什么被折叠?



