更改我的应用程序中所有textview的字体?

时间:2013-10-30 18:54:05

标签: android android-layout textview android-theme android-styles

我想知道是否有办法在单个时间内更改Android应用程序中所有文本视图的字体?通过所有文本视图,我的意思是以编程方式或动态创建的文本视图和使用XML布局文件单独创建的文本视图(拖放)?

我知道我可以用不同的必需字体创建一个新主题并使用它。但我只能看到主题适用于程序中动态创建的文本视图,而不适用于XML布局中的那个。

如果有任何解决方案,请告诉我,或者唯一的选择是手动更改每个文本视图的字体。

1 个答案:

答案 0 :(得分:2)

最简单的方法是扩展TextView小部件:

public class FontTextView extends TextView {

private String mTypefacePath;

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

public FontTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setAttrs(context, attrs, 0);
    init(context);
}

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

private void setAttrs(Context context, AttributeSet attrs, int defStyle) {
    if (isInEditMode())
        return;
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FontTextView, defStyle, 0);
    mTypefacePath = a.getString(R.styleable.FontTextView_typeface);
    a.recycle();
}

private void init(Context context) {
    if (!TextUtils.isEmpty(mTypefacePath)) {
        try {
            setTypeface(Typeface.createFromAsset(context.getAssets(),
                    mTypefacePath));
        } catch (Exception ex) {
            // could not create the typeface from path
        }
    } 
}}

您还需要定义typeface属性。 请查看this以查看有用的解释。