15

I want to use a custom font in an Android app but using custom fonts seems to be a pain?! I can setup a custom font programmatically by adding it to each TextView -> lots of boilerplate code. I can create a new class CustomTextView extends TextView and add setTypeface in the constructor -> no xml context aware help for attributes anymore.

Is there another way to setup a custom font? By XML, by style, by theme?

Thanks in advance!

P.S. Is there a possibility to set an underline by XML?

GabrielWeis
  • 340
  • 1
  • 3
  • 13
  • Have you looked at styles? http://developer.android.com/guide/topics/ui/themes.html – Mohit Deshpande Apr 17 '11 at 15:03
  • Yes but I haven't found anything useful. Same as for underline. Seems that one has to solve it programmaticaly – GabrielWeis May 06 '11 at 08:22
  • It is really pain to do application-wide font change. I am trying to create a style which is changing typeface value of TextAppearance style by inheriting, the problem is accessing to the font which is located under /assets/fonts. I couldn't figure out how to access to ttf file in my style xml. – erkangur Jul 19 '11 at 11:30
  • Possible duplicate of http://stackoverflow.com/questions/3651086/android-using-custom-font – Drahakar Aug 02 '11 at 02:23
  • Underlying by XML is usually achieved by adding `` tags in string resources containing the text that will be assigned to `TextView`s. However, I came across some cases where the use of a custom font prevented those tags to work, and the only way to make a text (or a portion of it) underlined was to programmatically use `SpannableString` and `UnderlineSpan`. See http://stackoverflow.com/a/10019093/22904 for an example of how to work with those classes. – Giulio Piancastelli Apr 02 '14 at 18:12

2 Answers2

12

use this code for change font textview..

TextView newfont;
newfont=(TextView) findViewById(R.id.textView1);
Typeface font=Typeface.createFromAsset(getAssets(), "fonts/DejaVuSerif-Italic.ttf");
newfont.setTypeface(font);
newfont.setText("This is the new font Text");

download DejaVuSerif-Italic.ttf file from web and put in fonts folder in assets folder.

Kundan Chaudhary
  • 833
  • 8
  • 20
6

You can include custom fonts under assets/fonts and then using the code from

https://github.com/browep/AndroidCustomFontWidgets/

you can specify the font in your XML, e.g.

<com.github.browep.customfonts.view.FontableTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="This is in a custom font"
    app:font="MyFont-Bold.otf" />

The code supports FontableTextView and FontableButton, but it's quite easy to extend to support other widget types if you require.

Jonathan Caryl
  • 1,330
  • 3
  • 12
  • 30