How to change the font on the TextView?

前端 未结 16 732
清歌不尽
清歌不尽 2020-11-22 08:09

How to change the font in a TextView, as default it\'s shown up as Arial? How to change it to Helvetica?

16条回答
  •  情歌与酒
    2020-11-22 08:25

    Another way to consolidate font creation...

    public class Font {
      public static final Font  PROXIMA_NOVA    = new Font("ProximaNovaRegular.otf");
      public static final Font  FRANKLIN_GOTHIC = new Font("FranklinGothicURWBoo.ttf");
      private final String      assetName;
      private volatile Typeface typeface;
    
      private Font(String assetName) {
        this.assetName = assetName;
      }
    
      public void apply(Context context, TextView textView) {
        if (typeface == null) {
          synchronized (this) {
            if (typeface == null) {
              typeface = Typeface.createFromAsset(context.getAssets(), assetName);
            }
          }
        }
        textView.setTypeface(typeface);
      }
    }
    

    And then to use in your activity...

    myTextView = (TextView) findViewById(R.id.myTextView);
    Font.PROXIMA_NOVA.apply(this, myTextView);
    

    Mind you, this double-checked locking idiom with the volatile field only works correctly with the memory model used in Java 1.5+.

提交回复
热议问题