Android - Using Custom Font

2020-01-22 11:40发布

I applied a custom font to a TextView, but it doesn't seems to change the typeface.

Here is my code:

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
    TextView myTextView = (TextView)findViewById(R.id.myTextView);
    myTextView.setTypeface(myTypeface);

Can anyone please get me out of this issue?

21条回答
孤傲高冷的网名
2楼-- · 2020-01-22 12:28

Well, after seven years you can change whole app textView or what you want easily by using android.support libraries 26++.

E.g:

Create your font package app/src/res/font and move your font into it.

enter image description here

And in your app theme just add it as a fontFamily:

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   . . . ...
    <item name="android:fontFamily">@font/demo</item>
</style>

Example for use with textView only:

<style name="fontTextView" parent="@android:style/Widget.TextView">
    <item name="android:fontFamily">monospace</item>
</style>

And add into your main theme:

<item name="android:textViewStyle">@style/fontTextView</item>

Currently it's worked on 8.1 until 4.1 API Jelly Bean And that's a wide range.

查看更多
何必那么认真
3楼-- · 2020-01-22 12:29

I had the same problem, the TTF did not show up. I changed the font file, and with the same code it's working.

查看更多
Fickle 薄情
4楼-- · 2020-01-22 12:29

Yes, downloadable fonts are so easy, as Dipali s said.

This is how you do it...

  1. Place a TextView.
  2. In the properties pane, select the fontFamily dropdown. If it isn't there, find the caret thingy (the > and click on it to expand textAppearance) under the.
  3. Expand the font-family drop down.
  4. In the little list, scroll all the way down till you see more fonts
  5. This will open up a dialog box where you can search from Google Fonts
  6. Search for the font you like with the search bar at the top
  7. Select your font.
  8. Select the style of the font you like (i.e. bold, normal, italic, etc)
  9. In the right pane, choose the radio button that says Add font to project
  10. Click okay. Now your TextView has the font you like!

BONUS: If you would like to style EVERYTHING with text in your application with chosen font, just add <item name="android:fontfamily">@font/fontnamehere</item> into your styles.xml

查看更多
登录 后发表回答