Question

I have a custom View class that extends Button. I'd like to set a custom Typeface to all instances of this class, but since some methods get called multiple times in a view, I was wondering what is the best overwriting method to place the following code in?

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

Currently, I have it in onMeasure(), but I noticed it gets called multiple times, which I assume won't be good for performance.

Était-ce utile?

La solution

Most correct is to add your code to constructor.

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;
    }

}

here customFont - is my custom attribute. i specify font from layout using this attr. I just created following custom attr in values/attrs.xml

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top