Android系统的字号可以在设置里改变,常常会影响布局效果。
如果是个别控件不想被改变大小,使用 dp 而非 sp 作为字体单位即可。
转载请注明出处:http://blog.csdn.net/u013258802/article/details/53395878
最近想只保持某一个页面的字号不被改变,又不想使用dp作字号单位,于是搜了下纯code的方案。
网上常见的方式是通过resource获取configuration,调用setToDefaults()方法:
Resources res = context.getResources();
Configuration config = res.getConfiguration();
config.setToDefaults();
res.updateConfiguration(config, res.getDisplayMetrics());
在 setContentView() 之前调用。
但是这样会改变整个APP的字号,也就是说,在执行完这几句代码后,除非杀进程,否则你后续都会看到默认字号,而我只想改变某一个页面的字号。
思路很简单,在该页面的onCreate()方法中获取设置进行缓存,在页面关闭时恢复即可。
由于Configuration类不可继承,也没有实现Cloneable接口,因此直接保存整个设置比较麻烦,需要用到反射或序列化,所以这里简化一下:
Configuration的setToDefaults()方法重置了很多不必要的属性,我们只需要对fontScale进行更改。
onCreate()方法内获取当前系统设置,mFontSize变量用于保存:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resizeFontSize(this);
setContentView(R.layout.activity_pos_detail);
...
private float mFontSize = 1.0f;
private void resizeFontSize(Context context) {
Resources res = context.getResources();
Configuration config = res.getConfiguration();
mFontSize = config.fontScale;
config.fontScale = 1.0f;// 默认字体尺寸值为1.0f
res.updateConfiguration(config, res.getDisplayMetrics());
}
onPause()方法内恢复:
@Override
protected void onPause() {
super.onPause();
reloadFontSize(this);
}
private void reloadFontSize(Context context) {
Resources res = context.getResources();
Configuration config = res.getConfiguration();
config.fontScale = mFontSize;
res.updateConfiguration(config, res.getDisplayMetrics());
}
运行一下,没毛病~
不过最后考虑再三,还是选择了在BaseActivity中重写getResource()方法:
/**
* 重置App界面的字体大小,fontScale 值为 1 代表默认字体大小
* @return
*/
@Override
public Resources getResources() {
Resources res = super.getResources();
Configuration config = res.getConfiguration();
config.fontScale = 1;
res.updateConfiguration(config, res.getDisplayMetrics());
return res;
}
简单粗暴地拒绝了字体更改带来的各种问题。。。