【问题标题】:Change font of entire application [duplicate]更改整个应用程序的字体[重复]
【发布时间】:2014-11-12 09:53:01
【问题描述】:

我想在我的应用程序中使用自定义字体。这是为整个应用程序提供字体的最佳方式。我知道如何将自定义字体分配给单个 TextView 或 Button。

是否可以在一处提及自定义字体,例如。在 styles.xml 中,字体将应用于整个应用程序(每个 TextView、Button、EditText 等等)。

【问题讨论】:

标签: android fonts styles custom-font


【解决方案1】:

在你的应用中使用这种类型的文本视图

public class MyTextView extends TextView {

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

public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

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

public void init() {
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/chiller.ttf");
    setTypeface(tf ,1);

}

}

也可以编辑文本

public class CEditText extends EditText {


private Context context;
private AttributeSet attrs;
private int defStyle;

public CEditText(Context context) {
    super(context);
    this.context=context;
    init();
} 

 public CEditText(Context context, AttributeSet attrs) {
      super(context, attrs);
      this.context=context;
      this.attrs=attrs;
      init();
 }

public CEditText(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      this.context=context;
      this.attrs=attrs;
      this.defStyle=defStyle;
      init();
}

private void init() {
      Typeface font=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
      this.setTypeface(font);
}
@Override
public void setTypeface(Typeface tf, int style) {
    tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
    super.setTypeface(tf, style);
}

@Override
public void setTypeface(Typeface tf) {
    tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf");
    super.setTypeface(tf);
}

【讨论】:

  • 另外,在布局 xml 文件中应该使用 加载
  • 我知道这种方法,谢谢。 Buttons 和 EditText 呢?我是否也必须制作自定义 EditText 和按钮?
  • 是的,这在 android 中称为 coustem 视图,使用任何 xml 文件
  • 我喜欢人们将别人的答案作为自己的答案发布......而不是将问题标记为重复 stackoverflow.com/questions/6926263/… 我什至给它起了个名字:偷窃
【解决方案2】:

不幸的是,android 没有提供任何方法来在一个地方为整个应用应用自定义字体。

但是,您可以创建 CustomTextView 扩展 TextView 和 CustomButton 扩展 Button。您可以通过创建 FontInstance 来设置字体。

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 2017-03-06
    • 2015-09-22
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多