Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom fonts on EditText in Android?

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);

Because I have lots of EditTexts...

like image 346
user1592261 Avatar asked May 13 '14 10:05

user1592261


2 Answers

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);
    }

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>
like image 175
Sainath Patwary karnate Avatar answered Oct 24 '22 22:10

Sainath Patwary karnate


Create a new class that extends EditText like

public class CustomEditTextNormal extends EditText
{

  public CustomEditTextNormal(Context context)
  {
      super(context);
      init(context);
  }

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

  public CustomEditTextNormal(Context context, AttributeSet attrs, int defStyle)
  {
    super(context, attrs, defStyle);
    init(context);
  }

  protected void onDraw(Canvas canvas)
  {
    super.onDraw(canvas);
  }

  public void init(Context context)
  {
    try
    {
        Typeface myFont = Typeface.createFromAsset(context.getAssets(), "fonts/myfont.ttf");

        setTypeface(mSearchAndSend.HelveticaLight);
    }
    catch (Exception e)
    {
        Logger.LogError(e);
    }
  }
}

and include it on your XML like

<com.package.name.CustomEditText/>
like image 45
Apoorv Avatar answered Oct 24 '22 23:10

Apoorv