为了账号安全,请及时绑定邮箱和手机立即绑定

Android中的自定义字体

Android中的自定义字体

智慧大石 2019-12-27 10:05:03
我已经阅读了一些文章并在Google上进行了搜索,但是我没有这样做。我的问题是关于字体。在Android中,“ "android:typeface"Normal”,“ Sans”,“ Serif”,“ Monospace” 中只有4个属性。那么,在应用程序中使用“ Verdana”该怎么办?请建议我在Android应用程序中使用此字体的正确方法。
查看完整描述

3 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

好!!

这个问题已经很老了,但是如果有人(2015年)正在寻找有关如何通过xml代码将自定义字体应用于所有Textview的答案,请直接参见以下内容:


首先:

我们需要在您的应用目录中的assets文件夹内添加自定义字体:

.ttf或.otf都适用于Android


第二:

创建Class CustomTextView,它扩展了TextView,如下所示:


public class CustomTextView extends TextView {


public CustomTextView(Context context) {

    super(context);

   }


public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr)   {

    super(context, attrs, defStyleAttr);

   }


public CustomTextView(Context context, AttributeSet attrs) {

    super(context, attrs);

   }


@Override

public void setTypeface(Typeface tf) {

    super.setTypeface(FontCache.getFont(getContext(),"fonts/<font_name>"));

   }

 }

第三:

在CustomTextView的setTypeface()方法中使用FontCache类,目的是使用HashMap进行基本的字体缓存:


public class FontCache {


private static Map<String,Typeface> fontMap = new HashMap<String,Typeface>();


public static Typeface getFont(Context context,String fontname){

    if(fontMap.containsKey(fontname)){

        return fontMap.get(fontname);

       }

    else{

        Typeface tf = Typeface.createFromAsset(context.getAssets(),fontname);

        fontMap.put(fontname,tf);

        return tf;

      }

    }

}

第四: [最后一步]现在要做的就是在需要自定义字体textview的地方直接在XML文件中使用CustomTextView:


<<package_name>.CustomTextView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Custom Font Text"

    android:textSize ="18sp"

    android:textAppearance="?android:textAppearanceSmall"

    android:id="@+id/custom_txt"

   />

抱歉,如果此消息已发布在SO的某个位置。只是想分享一下是否有帮助!!


查看完整回答
反对 回复 2019-12-27
  • 3 回答
  • 0 关注
  • 482 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信