Android 文档并未具体说明通过用户在应用程序级别选择全局更改字体大小的最有效方法。
我认为Black Devil给出的answer有问题。
问题在于许多Android 小部件子类TextView,例如Button、RadioButton 和CheckBox。其中一些是TextView 的间接子类,这使得在这些类中实现TextView 的定制版本非常困难。
然而,正如Siddharth Lele 在他的评论中指出的,使用styles 或themes 是处理整个应用中文本大小变化的更好方法。
我们为布局设置样式以控制视图的外观。主题本质上只是这些样式的集合。但是,我们可以将主题仅用于文本大小设置;没有为每个属性定义值。使用主题而不是样式为我们提供了一个巨大的优势:我们可以以编程方式为整个视图设置主题。
theme.xml
<resources>
<style name="FontSizeSmall">
<item name="android:textSize">12sp</item>
</style>
<style name="FontSizeMedium">
<item name="android:textSize">16sp</item>
</style>
<style name="FontSizeLarge">
<item name="android:textSize">20sp</item>
</style>
</resources>
创建一个类来处理加载我们的首选项:
public class BaseActivity extends Activity {
@Override
public void onStart() {
super.onStart();
// Enclose everything in a try block so we can just
// use the default view if anything goes wrong.
try {
// Get the font size value from SharedPreferences.
SharedPreferences settings =
getSharedPreferences("com.example.YourAppPackage", Context.MODE_PRIVATE);
// Get the font size option. We use "FONT_SIZE" as the key.
// Make sure to use this key when you set the value in SharedPreferences.
// We specify "Medium" as the default value, if it does not exist.
String fontSizePref = settings.getString("FONT_SIZE", "Medium");
// Select the proper theme ID.
// These will correspond to your theme names as defined in themes.xml.
int themeID = R.style.FontSizeMedium;
if (fontSizePref == "Small") {
themeID = R.style.FontSizeSmall;
}
else if (fontSizePref == "Large") {
themeID = R.style.FontSizeLarge;
}
// Set the theme for the activity.
setTheme(themeID);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
最后,通过扩展 BaseActivity 创建活动,如下所示:
public class AppActivity extends BaseActivity{
}
由于大多数应用程序的活动数量比 TextView 或继承 TextView 的小部件少得多。随着复杂性的增加,这将呈指数级增长,因此此解决方案需要的代码更改更少。
感谢Ray Kuhnell