项目适配遇到的问题,在Android 4.0以上的系统当中,用户能够在系统设置对字体大小进行更改,这样一来,在自己的应用当中由于字体大小的变化会导致显示不全,布局错乱等问题的存在。这个设置直接会影响到所有sp为单位的字体适配,所以很多app在设置了系统字体后瞬间变得面目全非。
虽然google推荐使用sp作为字体的单位,但实际的开发过程中通常是根据UI的设计稿来换算 sp(px换算sp)。而sp即使在同一种密度下其值也不尽相同。比如在240dpi的设备,如果是480x800分辨率这个值通常是1.5倍 (scaledDensity=1.5),如果是480xZ(z>800)那么这个值有可能大于1.5。这无疑给设备的适配带来更多的困难和陷阱。所以个人通常建议使用dpi来作为字体的单位。
默认情况下,字体跟随系统设置,对于个别app不需要根据系统字体的大小来改变的,可以在activity基类(app中所有的activity都应该有继承于我们自己定义的一个BaseActivity类)中加上以下代码:
@Override
public Resources getResources() {
Resources res = super.getResources();
Configuration config=new Configuration();
config.setToDefaults();
res.updateConfiguration(config,res.getDisplayMetrics() );
return res;
}
当然,我们可以提供配置项供用户选择是否字体大小跟随系统。
以下是一个例子:
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="字体设置(重启应用生效)" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跟随系统设置" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="不跟随系统设置" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"