Android Studio 通过布局编辑器设置字体系列

Android Studio set fontfamily via layout editor

目前我正在使用

为运行时设置字体
@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    Typeface customFont = Typeface.createFromAsset(getContext().getAssets(), "fonts/customFont.otf");
    this.customTxtView.setTypeface(customFont);
}

但该字体不会反映在 Android Studio 的布局编辑器中。我已经尝试使用与我在代码中使用的相同的值设置 android:typeface 以及 android:fontFamily 但无济于事。

布局生成器是否可以反映自定义字体更改?

根据How to change fontFamily of TextView in Android

From android 4.1 / 4.2 / 5.0, the following Roboto font families are available:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-thin"      // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium"    // roboto medium (android 5.0)

in combination with

android:textStyle="normal|bold|italic"

this 14 variants are possible:

  • Roboto regular
  • Roboto italic
  • Roboto bold
  • Roboto bold italic
  • Roboto-Light
  • Roboto-Light italic
  • Roboto-Thin
  • Roboto-Thin italic
  • Roboto-Condensed
  • Roboto-Condensed italic
  • Roboto-Condensed bold
  • Roboto-Condensed bold italic
  • Roboto-Medium
  • Roboto-Medium italic

注意:还有 robotium-thin 类型空间。


但是我看到你想使用你的自定义字体,所以你也会发现:

Android doesn't allow you to set custom fonts from the XML layout. Instead, you must bundle the specific font file in your app's assets folder, and set it programmatically. Something like:

TextView textView = (TextView) findViewById(<your TextView ID>);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
textView.setTypeface(typeFace);

Note that you can only run this code after setContentView() has been called. Also, only some fonts are supported by Android, and should be in a .ttf (TrueType) or .otf (OpenType) format. Even then, some fonts may not work.

This is a font that definitely works on Android, and you can use this to confirm that your code is working in case your font file isn't supported by Android.

如果这post对您没有帮助,请尽管说

TextView 被 select 编辑时,您应该会在右侧看到 textAppearance 属性。您可以 select 预定义的文本外观或展开该组并仅指定字体系列。