Android上的自定义字体 - 扩展TextView

1、将自定义字体应用于所有TextView

应用中我们会经常用到自定义字体的TextView。我们需要每次都去设置TextView的字体。但是,如果您在整个应用程序中多次使用它,那么效率低下(多次分配fontface)和代码(重复相同的代码)是无效的。

2、提供字体内存高效

Android手机内存低的时候已经结束了,但是我们还是应该优化效率。因此,我们应该缓存我们的自定义字体。来自britzl的stackoverflow( britzl on stackoverflow )的解决方案,并调整了一点写法:

public class FontCache {
    private static HashMap<String, Typeface> fontCache = new HashMap<>();
    public static Typeface getTypeface(String fontname, Context context) {
        Typeface typeface = fontCache.get(fontname);
        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), fontname);
            } catch (Exception e) {
                return null;
            }
            fontCache.put(fontname, typeface);
        }
        return typeface;
    }
}

这将缓存字体,同时最小化对assets文件夹的访问次数。现在,由于我们有一种访问我们的自定义字体的方法,我们来实现一个扩展TextView的类。

3、扩展TextView

接下来,我们将创建一个新的Java类,它扩展了TextView。这允许我们在所有XML视图中使用该类。它继承了常规TextView的所有功能和属性;但添加我们的自定义字体。

public class CustomTextView extends TextView {

    public CustomTextView(Context context) {
        super(context);
        applyCustomFont(context);
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        applyCustomFont(context);
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        applyCustomFont(context);
    }

    private void applyCustomFont(Context context) {
        Typeface customFont = FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
        setTypeface(customFont);
    }
}

它从我们的FontCache类获得(希望缓存)字体。最后,我们必须使用字体调用setTypeface()。

4、使用类

只需在XML视图中使用该类,它会自动使用您的自定义字体。没有必要的Java代码!

<RelativeLayout  
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.custom.views.CustomTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/green_dark"
        android:textSize="20sp"
        android:text="Android Studio"
        />

</RelativeLayout>  

您可以看到,您可以继续使用TextView的所有细节(例如textSize,textColor)。现在,只需使用我们刚刚创建的类替换所有<TextView />元素,例如<com.custom.views.CustomTextView />,并且您随时应用自定义字体!
好了,自定义字体的TextView到这里就结束了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,353评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,948评论 18 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,245评论 4 61
  • 【彼尚語錄】關於金錢 宇宙的錢像一個大大的管道,這個管道上有很多門,一開始這些門是敞開的,但隨著負面信念系統越來越...
    莹火蟲儿阅读 394评论 1 0
  • 今年,我21周岁,没有男朋友,已经上了大四,即将毕业,开始了人生的另一段旅程,也就是说我快工作了,然而目前工...
    乖乖女的小情调阅读 512评论 0 0