zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Android 理解DP、SP、PX的区别

Android 区别 理解 DP sp px
2023-09-14 09:13:59 时间

基础概念:

dp:最常用的长、宽、margin、padding等的单位
sp:字体的单位,和dp差不多,区别是如果字体使用的sp为单位,那如果你手机字体调大了,那你app的字体会随之变大,如果用dp则不会变化
px:像素

dp、sp、px的Button XML代码如下:

    <Button
        android:layout_width="150dp"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="150sp"
        android:layout_height="wrap_content"/>

    <Button
        android:layout_width="150px"
        android:layout_height="wrap_content"/>

测试如下:
在这里插入图片描述

dp、sp、px的TextView XML代码如下:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="Test dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Test sp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20px"
        android:text="Test px"/>

测试如下:
在这里插入图片描述