通过设置菜单更改应用程序的字体

时间:2017-11-27 11:30:56

标签: java android android-fonts

我尝试实现一项功能,用户可以激活“阅读障碍”模式,该模式会将整个应用程序的字体更改为res中保存为.tff文件的字体。

从阅读中看,这似乎是一项非常艰巨的任务。我已经明白可以在整个应用程序中使用自定义字体(from here),但根据我对此示例的理解,它不适合通过切换字体一个onClick方法。

有没有办法通过按钮触发这样做?

1 个答案:

答案 0 :(得分:0)

您可以使用自己的类扩展TextView,在项目的任何位置使用它。

public class MyTextView extends TextView {

   public MyTextView(Context context, AttributeSet attrs, int defStyle) {
       super(context, attrs, defStyle);
       init(context);
   }

   public MyTextView(Context context, AttributeSet attrs) {
       super(context, attrs);
       init(context);
   }

   public MyTextView(Context context) {
       super(context);
       init(context);
   }

   private void init(Context context) {
       Typeface tf =
       Typeface.createFromAsset(context.getAssets(), getFontFromPreferences(context));
       setTypeface(tf);
   }

   private String getFontFromPreferences(Context context) {
       SharedPreferences preferences = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);   
       String fontString = preferences.getString("my_font_pref_key", "Default.tff");
       return fontString;
   }
}

在您的设置按钮中,只需在SharedPreferences中设置新字体。