在运行时为Textview更改字体

时间:2016-08-03 07:50:03

标签: android textview android-fonts android-typeface

我有一个自定义TextView,我从我的服务器上获取了所有文本,所以我永远不知道会有什么样的风格。例如,这可以包括bolditalic和更多Textstyles。但我真的不确定如何在运行时处理它。

我创建了一个assets文件夹,其中包含我想要使用的所有字体:

enter image description here

在我的CustomTextView中我试过这样的事情:

public class CustomTextView extends TextView {

private static final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android";

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

    applyCustomFont(context, null);
}

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

    applyCustomFont(context, attrs);
}

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

    applyCustomFont(context, attrs);
}

private void applyCustomFont(Context context, AttributeSet attrs) {

    //Workaround for Preview Mode
    if (!isInEditMode()) {
        int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);

        Typeface customFont = selectTypeface(context, textStyle);
        setTypeface(customFont);

    } else {

        this.setTypeface(null, Typeface.NORMAL);
    }
}

private Typeface selectTypeface(Context context, int textStyle) {

    switch (textStyle) {
        case Typeface.BOLD: // bold
            return FontCache.getTypeface("fonts/OpenSans-Bold.ttf", context);

        case Typeface.ITALIC: // italic
            return FontCache.getTypeface("fonts/OpenSans-Italic.ttf", context);

        default:
            return FontCache.getTypeface("fonts/OpenSans-Regular.ttf", context);
    }
}

}

这是我的FontCache类:

public class FontCache {

//This caches the fonts while minimizing the number of accesses to the assets

private static final 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;
}

 }

但那不是它的工作方式,任何想法如何实现这一目标? 谢谢!

1 个答案:

答案 0 :(得分:1)

您可以覆盖setTypeface(Typeface tf, int style)

@Override
public void setTypeface(Typeface tf, int style) {
    Typeface customFont = selectTypeface(context, textStyle)
    super.setTypeface(customFont, style);
}

从外面你可以称之为

 mTextView.setTypeface(null, Typeface.BOLD);
相关问题