zoukankan      html  css  js  c++  java
  • 修改 字体

    例子一:

    快速修改整个页面所有的字体

    将字体文件放在assets文件夹中的fonts文件夹之下;

    首先编写一个工具类:

    package com.example.m_evolution.Utils;
    
    import android.app.Activity;
    import android.graphics.Typeface;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class FontManager {
    
        public static void changeFonts(ViewGroup root, Activity act) {
    
           Typeface tf = Typeface.createFromAsset(act.getAssets(),
                  "fonts/pingfang_light.ttf");
    
           for (int i = 0; i < root.getChildCount(); i++) {   
               View v = root.getChildAt(i);
               if (v instanceof TextView) {   
                  ((TextView) v).setTypeface(tf);
               } else if (v instanceof Button) {
                  ((Button) v).setTypeface(tf);   
               } else if (v instanceof EditText) {
                  ((EditText) v).setTypeface(tf);   
               } else if (v instanceof ViewGroup) {   
                  changeFonts((ViewGroup) v, act);   
               }   
           }   
    
        }   
    }  

    思路,遍历ViewGroup中所有的子项,如果是TextView等控件就修改其字体,注意有可能子项也是ViewGroup;

    接着在Activity中调用:

    FontManager.changeFonts((ViewGroup) getWindow().getDecorView(),this);

     例子二:

    修改整个APP的字体

    在Application类中用自带的字体替换系统的serif字体:

    //修改字体
            Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/pingfang_light.ttf");
            try
            {
                Field field = Typeface.class.getDeclaredField("SERIF");
                field.setAccessible(true);
                field.set(null, typeface);
            }
            catch (NoSuchFieldException e)
            {
                e.printStackTrace();
            }
            catch (IllegalAccessException e)
            {
                e.printStackTrace();
            }

    然后在style.xml中配置App的样式:

        <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
            <item name="android:typeface">serif</item>
        </style>
  • 相关阅读:
    学习进度笔记06
    学习进度笔记05
    学习进度笔记04
    学习进度笔记03
    学习进度笔记02
    周总结13
    周总结12
    周总结11
    人月神话阅读笔记3
    第一阶段冲刺10
  • 原文地址:https://www.cnblogs.com/zhaozilongcjiajia/p/10838151.html
Copyright © 2011-2022 走看看