如何在将按钮字体添加到视图组后对其进行更改?



给定在运行时创建的Button

Button button = Button(context)

设置自定义字体的方法是:

button.setTypeface(myTypeface)

然而,我发现它只在之前的工作。我将它添加到ViewGroup,而在之后的

我也试过:

button.setTypeface(myTypeface, myStyle) 

但也没用。我需要动态更改我的Button字体。我试过invalidate()requestLayout(),但字体从未改变。

解决方案:-您可以使用自定义字体将Button类划分为子类,并使用它来代替按钮

public class MyButton extends AppCompatButton {
public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyButton(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf");
setTypeface(tf);
}
}
}

最新更新