当前位置: 移动技术网 > 移动技术>移动开发>Android > 浅析Android加载字体包及封装的方法

浅析Android加载字体包及封装的方法

2020年06月23日  | 移动技术网移动技术  | 我要评论

textview加载字体包

在 android 中,若需要使得某个textview加载字体包,使用以下方式即可:

 typeface typeface =typeface.createfromasset(getassets(),"fonts/bold.otf");
  textview.settypeface(typeface);

至于字体包的位置:

通过以上方法,可以使得一个textview加载某种字体包,但是,还有这种需求:

  • 部分textview加载字体包
  • 每个textview加载的字体包不一定一样

这时,我们就需要稍微封装下,将其封装成一个自定义textview类,若需要使用字体包,则加载该类,同时,可以根据xml里面的值,从而加载不同的字体包。

封装

定义属性值

首先,我们需要从xml里面获取值,因此,需要在attr中进行属性值的定义:

<declare-styleable name="fonttextview">
  <attr name="fonttype" format="enum">
   <enum name="bold" value="1" />
   <enum name="heavy" value="2" />
  </attr>
 </declare-styleable>

这里我只定义了两种属性,大家可以根据需求进行增减。

创建自定义textview

public class fonttextview extends appcompattextview {

 public fonttextview(context context) {
  super(context);
 }
 public fonttextview(context context, @nullable attributeset attrs) {
  this(context, attrs, 0);
 }
 public fonttextview(context context, @nullable attributeset attrs, int defstyleattr) {
  super(context, attrs, defstyleattr);
 }
}

获取属性值

//获取参数
  typedarray a = context.obtainstyledattributes(attrs,
    r.styleable.fonttextview, defstyleattr, 0);

  int fonttype = a.getint(r.styleable.fonttextview_fonttype, 1);

进行值判断并加载不同的字体包

private final int bold = 1;
 private final int heavy = 2;
 
 string fontpath = null;
  switch (fonttype) {
   case bold:
    fontpath = "fonts/bold.otf";
    break;
   case heavy:
    fontpath = "fonts/heavy.otf";
    break;
   default:
  }
  //设置字体
  if (!textutils.isempty(fontpath)) {
   typeface typeface = typeface.createfromasset(getcontext().getassets(), fontpath);
   settypeface(typeface);
  }

全部源码

public class fonttextview extends appcompattextview {

 private final int bold = 1;

 private final int heavy = 2;

 public fonttextview(context context) {
  super(context);
 }

 public fonttextview(context context, @nullable attributeset attrs) {
  this(context, attrs, 0);
 }

 public fonttextview(context context, @nullable attributeset attrs, int defstyleattr) {
  super(context, attrs, defstyleattr);

  //获取参数
  typedarray a = context.obtainstyledattributes(attrs,
    r.styleable.fonttextview, defstyleattr, 0);

  int fonttype = a.getint(r.styleable.fonttextview_fonttype, 1);

  string fontpath = null;
  switch (fonttype) {
   case bold:
    fontpath = "fonts/bold.otf";
    break;
   case heavy:
    fontpath = "fonts/heavy.otf";
    break;
   default:
  }
  //设置字体
  if (!textutils.isempty(fontpath)) {
   typeface typeface = typeface.createfromasset(getcontext().getassets(), fontpath);
   settypeface(typeface);

  }
 }
}

若需要使用字体包textview,使用以下方式即可:

<com.jm.core.common.widget.textview.fonttextview
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  app:fonttype="bold"
  android:text="测试" />

效果

到此这篇关于浅析android加载字体包及封装的方法的文章就介绍到这了,更多相关android加载字体包封装内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网