【问题标题】:Easiest way to globally change Android font?全局更改Android字体的最简单方法?
【发布时间】:2011-12-29 01:18:07
【问题描述】:

我有一个 ttf 文件,它在理论上是可行的,但我不想触及 500 多行不同的代码来以编程方式更改它。最简单的方法是什么?

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/Typefaces.html

【问题讨论】:

    标签: android


    【解决方案1】:

    使用静态 TYPEFACE 扩展 previous 答案:

    添加新功能:

    public static void applyCustomFont(ViewGroup list, Typeface customTypeface) {
                for (int i = 0; i < list.getChildCount(); i++) {
                    View view = list.getChildAt(i);
                    if (view instanceof ViewGroup) {
                        applyCustomFont((ViewGroup) view, customTypeface);
                    } else if (view instanceof TextView) {
                        ((TextView) view).setTypeface(customTypeface);
                    }
                }
            }
    

    获取我们布局的根视图:

    View rootView = findViewById(android.R.id.content)
    

    比对带有所有子元素的整个活动表单应用自定义字体:

    applyCustomFont((ViewGroup)rootView, C.TYPEFACE.ArialRounded(this));
    

    【讨论】:

      【解决方案2】:

      我自己处理过这个问题;虽然我无法全局设置自定义字体,但我可以让它更容易处理。

      所以在我的常量类(C.java)中我有一个内部类:

      public static final class TYPEFACE {
          public static final Typeface Helvetica(Context ctx){
              Typeface typeface = Typeface.createFromAsset(ctx.getAssets(), "helvetica.otf");
              return typeface;
          }
          public static final Typeface ArialRounded(Context ctx){
              Typeface typeface = Typeface.createFromAsset(ctx.getAssets(), "arial_rounded.ttf");
              return typeface;
          }
      } 
      

      在我的代码中,在声明和初始化 TextView 之后,我只是将其设置为字体:

      TextView title = (TextView)findViewById(R.id.title);
      title.setTypeface(C.TYPEFACE.Helvetica(this));
      

      我知道这并不能解决您的问题,但我希望它可以帮助...

      -serkan

      【讨论】:

      • 我认为 serkan 有它。更改字体没有全局覆盖。如果您已经构建了应用程序,那么您将面临大量重构。
      • @serkan:为了安全起见,我会使用ctx.getApplicationContext().getAssets()。由于您将这些Typeface 对象存储在静态数据成员中,如果createFromAsset() 中的某些内容保留对传入Context 的引用,您将泄漏您在示例中使用的Activity。使用Application 对象更安全,因为它已经 一个全局实例并且不能泄露。而且,嗯,请确保您只使用获得分发许可的字体。
      • 没有为经常使用而优化的代码。最好将“Typeface typeface”设为静态最终并仅在“!= null”情况下初始化。这是我的修改:private static Typeface arialTypeface; public static final Typeface Arial(Context ctx) { if (arialTypeface == null) { arialTypeface = Typeface.createFromAsset(ctx.getAssets(), "fonts/arial.ttf"); } 返回 arialTypeface; }
      【解决方案3】:

      另一种方法是扩展 TextView 的自定义视图。不漂亮,但你不需要到处复制字体代码。

      总而言之,这是一个非常烦人的问题。

      【讨论】:

        猜你喜欢
        • 2012-04-27
        • 1970-01-01
        • 2019-02-17
        • 2012-12-15
        • 1970-01-01
        • 2011-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多