Android修改字体样式的示例代码

在Android实际开发中根据UI的设计图,经常要去改变系统默认的字体样式

这样做会使apk变大很多啊

而且为什么android要使用ios的字体-_-#

单独设置字体样式

(1)Android系统提供了几种字体样式可供选择

通过设置typeface属性或者fontFamily属性设置

typeface属性:

  1. normal
  2. serif
  3. sans
  4. monospace

fontFamily属性:

  1. casual
  2. cursive
  3. serif
  4. monospace
  5. sans-serif
  6. sans-serif-condensed
  7. serif-monospace
  8. sans-serif-smallcaps

在代码中设置

AssetManager mgr = getAssets();
Typeface tf = Typeface.createFromAsset(mgr,"fonts/NotoSansCJKsc-Black.otf");
tv_1.setTypeface(tf);

批量设置字体样式

(1)自定义TextView

public class CustomTextView extends TextView
{

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

  //重写设置字体方法
  @Override
  public void setTypeface(Typeface tf)
  {
    tf = Typeface.createFromAsset(getContext().getAssets(),"fonts/NotoSansCJKsc-Light.otf");
    super.setTypeface(tf);
  }
}

之后在XML布局文件中使用CustomTextView代替TextView

  <com.test.fontfamily.CustomTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="6dp"
    android:text="自定义字体"
    android:textSize="24dp"
    />

微信公众号搜索 “ 程序精选 ” ,选择关注!
精选程序员所需精品干货内容!