android - 在自定义 View 类中的何处设置自定义字体(扩展按钮)?

标签 android fonts android-view android-fonts

我有一个扩展 Button 的自定义 View 类。我想为此类的所有实例设置自定义字体,但由于某些方法在 View 中被多次调用,我想知道放置以下代码的最佳覆盖方法是什么?

    final Typeface face = Typeface.createFromAsset(getContext().getAssets(),
            "myfont.ttf");
    this.setTypeface(face);

目前,我在 onMeasure() 中有它,但我注意到它被多次调用,我认为这对性能不利。

最佳答案

最正确的做法是将代码添加到构造函数中。

public class ButtonPlus extends Button {

    public ButtonPlus(Context context) {
        super(context);
    }

    public ButtonPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public ButtonPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs,
                R.styleable.TextViewPlus);
        String customFont = a.getString(R.styleable.TextViewPlus_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
            tf = Typeface.createFromAsset(ctx.getAssets(), asset);
        } catch (Exception e) {
            return false;
        }

        setTypeface(tf);
        return true;
    }

}

这里的 customFont - 是我的自定义属性。我使用此 attr 从布局中指定字体。我刚刚在 values/attrs.xml 中创建了以下自定义属性

关于android - 在自定义 View 类中的何处设置自定义字体(扩展按钮)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920241/

相关文章:

Wi-Fi无法上网时Android Lollipop默认使用Mobile Data?

css - 文本呈现呈锯齿状

text - 如何将任何文本/字体转换为其贝塞尔路径表示?

android - 旋转后如何正确恢复 View 状态

android - RatingBar 变得半透明

android - 使用 Google API 创建 Google 应用内产品

java - 为相机应用程序获得相同的方向角

android - java.lang.NullPointerException : displaying records from database in an expandable listview 异常

fonts - Word 2010中Cambria Math斜体字体的区别

android - 嵌套坐标布局和fitsSystemWindows重叠状态栏