How to change the font on the TextView?

前端 未结 16 1067
清歌不尽
清歌不尽 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:47

    import java.lang.ref.WeakReference;
    import java.util.HashMap;
    
    import android.content.Context;
    import android.graphics.Typeface;
    
    public class FontsManager {
    
        private static FontsManager instance;
    
        private static HashMap> typefaces = new HashMap>();
    
        private static Context context;
    
        private FontsManager(final Context ctx) {
            if (context == null) {
                context = ctx;
            }
        }
    
        public static FontsManager getInstance(final Context appContext) {
            if (instance == null) {
                instance = new FontsManager(appContext);
            }
            return instance;
        }
    
        public static FontsManager getInstance() {
            if (instance == null) {
                throw new RuntimeException(
                        "Call getInstance(Context context) at least once to init the singleton properly");
            }
            return instance;
        }
    
        public Typeface getFont(final String assetName) {
            final WeakReference tfReference = typefaces.get(assetName);
            if (tfReference == null || tfReference.get() == null) {
                final Typeface tf = Typeface.createFromAsset(context.getResources().getAssets(),
                        assetName);
                typefaces.put(assetName, new WeakReference(tf));
                return tf;
            }
            return tfReference.get();
        }
    
    }
    

    This way, you can create a View which inherits from TextView and calls setTypeface on its constructor.

提交回复
热议问题