Android 在自定义视图类(扩展按钮)中的何处设置自定义字体?
我有一个自定义视图类,它扩展了Button。我想为这个类的所有实例设置一个自定义字体,但是由于一些方法在一个视图中被多次调用,我想知道放置以下代码的最佳覆盖方法是什么Android 在自定义视图类(扩展按钮)中的何处设置自定义字体?,android,fonts,android-view,android-fonts,Android,Fonts,Android View,Android Fonts,我有一个自定义视图类,它扩展了Button。我想为这个类的所有实例设置一个自定义字体,但是由于一些方法在一个视图中被多次调用,我想知道放置以下代码的最佳覆盖方法是什么 final Typeface face = Typeface.createFromAsset(getContext().getAssets(), "myfont.ttf"); this.setTypeface(face); 目前,我在onMeasure()中有它,但我注意到它被多次调用,我
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-是我的自定义属性。我使用这个属性从布局中指定字体。我刚刚在values/attrs.xml中创建了以下自定义attr