如何在Android中的EditText上设置自定义字体? [英] How to set custom fonts on EditText in Android?

查看:431
本文介绍了如何在Android中的EditText上设置自定义字体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在EditText上实现自定义字体.有没有人比我目前正在做的更好的方法?

I am trying to implement a custom typeface on an EditText. Does anyone have a better approach as opposed to what I'm currently doing?

Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
edittext.setTypeface(myFont);

因为我有很多EditText s ...

Because I have lots of EditTexts...

推荐答案

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调用此类,如下所示

call this class in XML as follows

<yourpackagename.CEditText  android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp">
</yourpackagename.CEditText>

这篇关于如何在Android中的EditText上设置自定义字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆