Android APP字体大小跟随系统设置

在Android 4.0以上系统中,用户可以修改字体大小,导致App可能显示不全或布局错乱。虽然使用sp作为字体单位是Google的推荐,但在不同密度设备上sp值会变化,增加适配难度。开发者可以选择在BaseActivity中设置字体不跟随系统,或者提供选项让用户自行选择。示例代码和布局文件展示了解决方案。
摘要由CSDN通过智能技术生成

  项目适配遇到的问题,在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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值