FontManager 给某个页面或某些控件更改字体

更改字体的方法:
public class FontsManager {

    public static final String TAG = "FontsManagerException";
    public static final String INIT_EXCEPTION = "FontsManager使用该函数前必须先进行初始化";
    /** 默认字体 */
    public static Typeface defaultTypeface = null;

    private FontsManager(){}

    //----初始化-------------------------------------------------------------------------
    /**
     * 初始化
     *
     * @Title: init
     * @param typeface 字体
     */
    public static void init(Typeface typeface){
        if (typeface == null) {
            Log.e(TAG, "typeface不能为空。");
            throw new IllegalStateException("typeface不能为空。");
        } else {
            defaultTypeface = typeface;
        }
    }

    /**
     * 初始化
     *
     * @Title: initFormAssets
     * @param context 上下文
     * @param fontPath Assets中字体包路径
     */
    public static void initFormAssets(Context context, String fontPath){
        try {
            defaultTypeface = Typeface.createFromAsset(context.getAssets(), fontPath);
        } catch (Exception e) {
            Log.e(TAG, "初始化失败,请检查fontsPath是否错误");
            throw new IllegalStateException("初始化失败,请检查fontsPath是否错误");
        }
    }

    /**
     * 初始化
     *
     * @Title: initFormFile
     * @param fontPath 字体包存放路径(例如:sdcard/font.ttf)
     */
    public static void initFormFile(String fontPath){
        try {
            defaultTypeface = Typeface.createFromFile(fontPath);
        } catch (Exception e) {
            Log.e(TAG, "初始化失败,请检查fontsPath是否错误");
            throw new IllegalStateException("初始化失败,请检查fontsPath是否错误");
        }
    }

    /**
     * 初始化
     *
     * @Title: initFormFile
     * @param fontPath 字体包文件
     */
    public static void initFormFile(File fontFile){
        try {
            defaultTypeface = Typeface.createFromFile(fontFile);
        } catch (Exception e) {
            Log.e(TAG, "初始化失败,请检查fontFile是否是字体文件");
            throw new IllegalStateException("初始化失败,请检查fontFile是否是字体文件");
        }
    }

    //----改变字体-------------------------------------------------------------------------
    /**
     * 更换字体
     *
     * @Title: changeFonts
     * @param activity
     */
    public static void changeFonts(Activity activity){
        if (defaultTypeface == null) {
            Log.e(TAG, INIT_EXCEPTION);
            throw new IllegalStateException(INIT_EXCEPTION);
        }
        //此行代码注释后不看到有什么变化
//        ActionBarHelper.changeTitleFonts(activity, defaultTypeface);
        changeFonts((ViewGroup) activity.findViewById(android.R.id.content), defaultTypeface);
    }

    /**
     * 更改字体
     *
     * @Title: changeFonts
     * @param view
     */
    public static void changeFonts(View view){
        if (defaultTypeface == null) {
            Log.e(TAG, INIT_EXCEPTION);
            throw new IllegalStateException(INIT_EXCEPTION);
        }
        changeFonts(view, defaultTypeface);
    }

    /**
     * 更改字体
     *
     * @Title: changeFonts
     * @param viewGroup
     */
    public static void changeFonts(ViewGroup viewGroup){
        if (defaultTypeface == null) {
            Log.e(TAG, INIT_EXCEPTION);
            throw new IllegalStateException(INIT_EXCEPTION);
        }
        changeFonts(viewGroup, defaultTypeface);
    }

    /**
     * 更换字体
     *
     * @Title: changeFonts
     * @param viewGroup
     * @param typeface
     */
    public static void changeFonts(ViewGroup viewGroup, Typeface typeface){
        try {
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                View v = viewGroup.getChildAt(i);
                if (v instanceof ViewGroup) {
                    changeFonts((ViewGroup) v, typeface);
                } else if (v instanceof View) {
                    changeFonts((View) v, typeface);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            // TODO
        }
    }

    /**
     * 更换字体
     *
     * @Title: changeFonts
     * @param view
     * @param typeface void
     */
    public static void changeFonts(View view, Typeface typeface){
        try {
            if (view instanceof ViewGroup) {
                changeFonts((ViewGroup) view, typeface);
            } else if (view instanceof TextView) {
                ((TextView) view).setTypeface(typeface);
            } else if (view instanceof Button) {
                ((Button) view).setTypeface(typeface);
            } else if (view instanceof Switch) {
                ((Switch) view).setTypeface(typeface);
            } else if (view instanceof EditText) {
                ((EditText) view).setTypeface(typeface);
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            // TODO
        }

    }
}
 
View页,点击按钮更改字体,字体放在与java目录平级的assets目录下:
public class FontManageDemoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_font_manage_demo);

        FontsManager.initFormAssets(FontManageDemoActivity.this,"fonts/sao.ttf");
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FontsManager.changeFonts(FontManageDemoActivity.this);
                Toast.makeText(FontManageDemoActivity.this,"替换成功",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

在网上查询到的资料中还有一个文件,但我使用后,没看到效果,该文件的调用在FontManager.java中的changeFonts(Activity activity)中:
@SuppressLint("DefaultLocale")
@SuppressWarnings("deprecation")
public class ActionBarHelper {

    private static final String TAG = "ActionBarHelper";
    public static final String INIT_EXCEPTION = "使用该函数前必须对FontsManager进行初始化";

    /**
     * 改变标题字体
     *
     * @Title: changeTitleFonts
     * @param activity
     * @param typeface
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void changeTitleFonts(Activity activity, Typeface typeface){
        if (typeface == null || activity == null) {
            Log.e(TAG, "activity或 typeface等于空!");
            return;
        }
        if (activity instanceof ActionBarActivity) {
            try {
                android.support.v7.app.ActionBar actionBar = ((ActionBarActivity) activity).getSupportActionBar();
                setTitle(actionBar, typeface, actionBar.getTitle().toString());
            } catch (Exception e) {
                Log.e(TAG, e.toString());
            }

        } else if (activity instanceof Activity) {
            try {
                ActionBar actionBar = activity.getActionBar();
                setTitle(actionBar, typeface, actionBar.getTitle().toString());
            } catch (Exception e) {
                Log.e(TAG, e.toString());
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void setTitle(Activity activity, Typeface typeface, String title){
        if (activity instanceof android.support.v7.app.ActionBarActivity) {
            try {
                android.support.v7.app.ActionBar actionBar = ((ActionBarActivity) activity).getSupportActionBar();
                setTitle(actionBar, typeface, title);
            } catch (Exception e) {
                Log.e(TAG, e.toString());
            }

        } else if (activity instanceof Activity) {
            try {
                ActionBar actionBar = activity.getActionBar();
                setTitle(actionBar, typeface, title);
            } catch (Exception e) {
                Log.e(TAG, e.toString());
            }
        }
    }

    public static void setTitle(android.support.v7.app.ActionBar actionBar, Typeface typeface, String title){
        if (typeface == null || actionBar == null) {
            Log.e(TAG, "typeface或actionbar为空");
            return;
        }
        SpannableString sp = new SpannableString(title);
        sp.setSpan(new TypefaceSpan(typeface), 0, sp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        setTitle(actionBar, sp);
    }

    public static void setTitle(ActionBar actionBar, Typeface typeface, String title){
        if (typeface == null || actionBar == null) {
            Log.e(TAG, "typeface或actionbar为空");
            return;
        }
        SpannableString sp = new SpannableString(title);
        sp.setSpan(new TypefaceSpan(typeface), 0, sp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        setTitle(actionBar, sp);
    }

    /**
     * 设置标题
     *
     * @Title: setTitle
     * @param actionBar
     * @param spannableString
     */
    public static void setTitle(android.support.v7.app.ActionBar actionBar, SpannableString spannableString){
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN && Build.MANUFACTURER.toUpperCase().equals("LGE")) {
            actionBar.setTitle(spannableString.toString());
        } else {
            actionBar.setTitle(spannableString);
        }
    }


    /**
     * 设置标题
     *
     * @Title: setTitle
     * @param actionBar
     * @param spannableString
     */
    @TargetApi(11)
    public static void setTitle(ActionBar actionBar, SpannableString spannableString){
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN && Build.MANUFACTURER.toUpperCase().equals("LGE")) {
            actionBar.setTitle(spannableString.toString());
        } else {
            actionBar.setTitle(spannableString);
        }
    }


    /**
     * 设置字体样式
     *
     * @ClassName: TypefaceSpan
     * @author: sloop
     * @website: http://www.sloop.icoc.cc
     * @weibo: http://weibo.com/u/5459430586
     * @date 2015年6月9日 下午12:11:13
     */
    private static class TypefaceSpan extends MetricAffectingSpan {

        Typeface typeface;

        TypefaceSpan(Typeface typeface){
            this.typeface = typeface;
        }

        @Override
        public void updateMeasureState(TextPaint p){
            p.setTypeface(typeface);
            p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }

        @Override
        public void updateDrawState(TextPaint tp){
            tp.setTypeface(typeface);
            tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值