您的位置:首页 > 移动开发 > Android开发

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

2016-01-21 23:32 501 查看
在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下载链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息