TextView 在Android中是很常用的基本工具
不過在textsize單位上大家都知道使用sp, 不過我在工作上有遇到設定為dp的方式
實在很神奇, 差別在哪呢
以下我做個測試
我寫了兩個 TextView 一個使用sp, 另一個用dp
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.owen.blogapp.MainActivity"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginTop="16dp" android:text="text 13sp" android:textSize="@dimen/test_text_size_sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="0dp" android:layout_marginTop="16dp" android:text="text 13dp" android:textSize="@dimen/test_text_size_dp" app:layout_constraintLeft_toLeftOf="@+id/textView2" app:layout_constraintTop_toBottomOf="@+id/textView2" /> </android.support.constraint.ConstraintLayout>
使用的單位為
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="test_text_size_sp">13sp</dimen> <dimen name="test_text_size_dp">13dp</dimen> </resources>
然後直接在模擬器上跑
預設的大小下, 兩種大小一樣


而我把文字大小放大

呈現效果如下

結論 :sp會根據裝置文字大小設定做調整
基本上使用sp就是會有動態字級效果
不過內建會提供三種size給開發者 Large, Medium, small 這三種Text Style
ps: 使用動態字及效果, 請小心字太大造成換行或超出view範圍
