Android设定字体大小,不随系统变化

本文介绍在Android应用开发中如何正确地设置字体大小,包括使用dp、sp和px单位的区别及应用场景,通过代码示例展示了如何根据需要选择合适的单位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在app开发中,我们经常会限定字体大小,不跟随系统设定的字号变化。所以在编写页面时,会经常使用dp,而不是sp;

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linear_context"
    android:orientation="vertical" >
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="25dp"/>
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="25sp"/>
</LinearLayout>

偶尔,也许会在代码中动态生成TextView,并设定了字体大小

tView=new TextView(this);
tView.setTextSize(25);
tView.setText("25 scaled pixel");

字体设置了,可我们并不知道设定的25到底是多大的,单位会是像素(px)吗?其实不是像素(px),而是缩放像素sp(scaled pixel),官方对SetTextSize的说明也是非常清楚的

Set the default text size to the given value, interpreted as “scaled pixel” units. This size is adjusted based on the current density and user font size preference.

那使用代码设置的字体单位只能是sp了吗?其实也不是,Android还有一个setTextSize的重载方法,可以通过设置单位了来限定字体的大小

tView.setTextSize(TypedValue.COMPLEX_UNIT_PX,22); //22像素 
tView.setTextSize(TypedValue.COMPLEX_UNIT_SP,22); //22SP 
tView.setTextSize(TypedValue.COMPLEX_UNIT_DIP,22);//22DIP 

这样,在代码中设置字体大小时,同时将字体大小的单位设置了dp,就可以固定字体大小不随系统设定的字号变化了

另一种可行的方法可以在Activity中,重写getResources方法,也可以达到固定字体大小的效果

@Override  
public Resources getResources() {  
    Resources res = super.getResources();    
    Configuration config=new Configuration();    
    config.setToDefaults();    
    res.updateConfiguration(config,res.getDisplayMetrics());  
    return res;  
}  

这里写图片描述

上图是所做的测试截图并配有说明,这里提供demo下载链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值