2

I wonder what would be the best way to assign a font typeface to a TextView view? Is it better to create a custom TextView class which extends TextView or use setTypeFace attribute?

Hamidreza
  • 1,360
  • 11
  • 18

3 Answers3

0

create folder assets(src/main/assets/ in AndroidStudio) and make a sub-folder fonts , copy your fonts in them

 Typeface tf = Typeface.createFromAsset(getAssets(),
    "fonts/youi.ttf");
 TextView tv = (TextView) findViewById(R.id.edit_t);
 tv.setTypeface(tf);
Nikhil Verma
  • 1,777
  • 1
  • 20
  • 41
  • 1
    I know this. Consider I have a ListView item xml file and there are TextViews inside. And I want to use custom fonts for each TextView, should I send typeface as an input to custom adapter class so then I can assign it by using the code you mentioned? – Hamidreza Apr 07 '15 at 17:44
  • Yes , Assign fonts in getView() . – Nikhil Verma Apr 07 '15 at 17:45
  • And if I have more than one font type, should I send a list of typefaces? Is it the best and easiest possible way? – Hamidreza Apr 07 '15 at 17:50
  • Please be careful as there is a known problem with `createFromAsset`. Instead of maintaining its reference, it tries to recreate the typeface each time it's called. You should probably cache it if you plan to use it often. – Alex Kolpa Apr 07 '15 at 17:51
  • See this : http://stackoverflow.com/questions/15293437/custom-font-for-android-listview – Nikhil Verma Apr 07 '15 at 17:55
  • @alex-kolpa What you mean exactly? Is it wrong to this in main activity and send fonts list to adapter? fontList = new ArrayList(); fontList.add(Typeface.createFromAsset(getAssets(), "fonts/gautami.ttf")); fontList.add(Typeface.createFromAsset(getAssets(), "fonts/clash.ttf")); fontList.add(Typeface.createFromAsset(getAssets(), "fonts/tekton_pro.otf")); – Hamidreza Apr 07 '15 at 17:58
  • No, that works fine in this case, since you're only creating each font once. But I have a few apps where I use custom fonts all over the place. For those cases I use [this solution](http://stackoverflow.com/a/17283657/4258911) – Alex Kolpa Apr 07 '15 at 18:00
  • I know. It's a good answer. But I'd like to hear more from different users. More opinions, better result. – Hamidreza Apr 07 '15 at 19:10
0

Here is the kotlin version for this

val openSansLight: Typeface by lazy { Typeface.createFromAsset(context, "font/os_light.ttf"); }
textView.typeface = openSansLight
Kavin Varnan
  • 1,989
  • 18
  • 23
0

Font is now part of the app resource! You can now use the font family attribute to change the typeface in xml. Create font resource directory and you can put font files in there.

android:fontFamily="@font/lobster"

Using code

val typeface = resources.getFont(R.font.myfont)
textView.typeface = typeface

Refer the official documentation for more

Samuel Robert
  • 10,106
  • 7
  • 39
  • 60