How to change fontFamily of TextView in Android

后端 未结 30 3085
感动是毒
感动是毒 2020-11-22 01:05

So I\'d like to change the android:fontFamily in Android but I don\'t see any pre-defined fonts in Android. How do I select one of the pre-defined ones? I don\'

30条回答
  •  我在风中等你
    2020-11-22 01:44

    Android doesn't allow you to set custom fonts from the XML layout. Instead, you must bundle the specific font file in your app's assets folder, and set it programmatically. Something like:

    TextView textView = (TextView) findViewById();
    Typeface typeFace = Typeface.createFromAsset(getAssets(), "");
    textView.setTypeface(typeFace);
    

    Note that you can only run this code after setContentView() has been called. Also, only some fonts are supported by Android, and should be in a .ttf (TrueType) or .otf (OpenType) format. Even then, some fonts may not work.

    This is a font that definitely works on Android, and you can use this to confirm that your code is working in case your font file isn't supported by Android.

    Android O Update: This is now possible with XML in Android O, based on Roger's comment.

提交回复
热议问题