Android设定字体大小,不随系统变化
2016-01-21 23:32
501 查看
在app开发中,我们经常会限定字体大小,不跟随系统设定的字号变化。所以在编写页面时,会经常使用dp,而不是sp;
偶尔,也许会在代码中动态生成TextView,并设定了字体大小
字体设置了,可我们并不知道设定的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的重载方法,可以通过设置单位了来限定字体的大小
这样,在代码中设置字体大小时,同时将字体大小的单位设置了dp,就可以固定字体大小不随系统设定的字号变化了
另一种可行的方法可以在Activity中,重写getResources方法,也可以达到固定字体大小的效果
上图是所做的测试截图并配有说明,这里提供demo下载链接
<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下载链接
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories