Android 自定义字体方案

CharleneEth 8年前
   <p>在应用中需要配置不同的字体,而 Android 只能在 xml 中配置系统默认提供的四种字体,需要自定义的字体都需要在 Java 代码中配置.</p>    <h2>Android 默认方案</h2>    <p>你可以通过ID查找到View,然后挨个为它们设置字体。字体放置于 assets/fonts 文件夹下面.</p>    <pre>  <code class="language-java">Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/YourCustomFont.ttf");  TextView view = (TextView) findViewById(R.id.activity_main_header);  view.setTypeface(customFont);</code></pre>    <h2>改良</h2>    <p>如果每次都这样加载,界面就会卡顿,所以我提取出来了一个工具类.</p>    <p>示例中涉及到了两个自定义的字体,用枚举实现了单例模式,将字体存储在静态变量中,避免每次都去 assets 中加载,更改之后页面就流畅了.</p>    <pre>  <code class="language-java">public enum TypefaceUtils {      TYPEFACE;        private static Typeface typeface50;      private static Typeface typeface55;        public void set50Typeface(TextView textView) {          if (typeface50 == null)              typeface50 = Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/HYQiHei-50S.otf");          textView.setTypeface(typeface50);      }        public void set55Typeface(TextView textView) {          if (typeface55 == null)              typeface55 = Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/HYQiHei-55S.otf");          textView.setTypeface(typeface55);      }  }</code></pre>    <h2>参考链接</h2>    <ul>     <li><a href="/misc/goto?guid=4959737366470740656" rel="nofollow,noindex">【译】Android:更好的自定义字体方案</a></li>     <li><a href="/misc/goto?guid=4959737366563546516" rel="nofollow,noindex">Android如何高效率的替换整个APP的字体?</a></li>    </ul>    <p> </p>    <p>来自:http://www.jianshu.com/p/6778d048d8c6</p>    <p> </p>