fonts - Android : Proper way to use custom typeface in -


what right way use typeface in android? see many examples using custom xml tag text view. tried to set in java normal text view , works fine, reason use custom fields?

when using custom typeface best add typeface /assets directory in project. lightweight following:

textview customtypefacetextview = (textview) findviewbyid(r.id.customtypefacetextview); typeface customtypeface = typeface.createfromasset(getassets(), "custom_typeface.ttf"); customtypefacetextview.settypeface(customtypeface); 

just remember finding assets related current context if using custom fonts in fragment vs. activity want call getactivity().getassets() instead of getassets().

this reference quick tip : http://code.tutsplus.com/tutorials/customize-android-fonts--mobile-1601

additionally may more practical create class extends textview have more practical implementation custom font can used textviews want add custom font so:

public class customtitletextview extends textview {  private context m_classcontext          = null; private typeface m_customtypeface       = null;      // default constructor public customtitletextview(context context) {     super(context);     // todo auto-generated constructor stub     this.m_classcontext = context;     createrobototitletextview(); }      // default constructor public customtitletextview(context context, attributeset attrs, int defstyle) {     super(context, attrs, defstyle);     // todo auto-generated constructor stub     this.m_classcontext = context;     createrobototitletextview(); }      // default constructor public customtitletextview(context context, attributeset attrs) {     super(context, attrs);     // todo auto-generated constructor stub     this.m_classcontext = context;     createrobototitletextview(); }      // adds typeface textview private void createrobototitletextview() {     m_customtypeface = typeface.createfromasset(m_classcontext.getassets(), "roboto-thin.ttf");     this.settypeface(m_customtypeface);  }   } 

and can use in xml in layout

<packagename.customtitletextview   android:id="@+id/customtitletextview"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/> 

update

these few ways have had success implementing custom fonts. sample showing how add custom textview via extends textview adding in xml not necessary provides skeleton of how create textview re-useable object rather doing dynamically in activity or fragment.

good luck!


Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -