Android 修改字体样式,看这篇就够了
Android 默认字体为「思源黑体」,英文名:Noto Sans
英文字体:Roboto 字体
修改字体步骤:
1.单独设置字体样式
(1)Android系统提供了几种字体样式可供选择
通过设置typeface属性或者fontFamily属性设置
typeface属性:
- normal
- serif
- sans
- monospace
fontFamily属性:
- casual
- cursive
- serif
- monospace
- sans-serif
- sans-serif-condensed
- serif-monospace
- sans-serif-smallcaps
※typeface和fontFamily区别
android:typeface属性是增加API1
android:fontFamily在API16(4.1)中添加了属性
※当同时设置typeface和fontFamily时,只有fontFamily生效
查看一波TextView的源码
private void setTypefaceFromAttrs(String familyName, int typefaceIndex, int styleIndex) {Typeface tf = null;if (familyName != null) {tf = Typeface.create(familyName, styleIndex);if (tf != null) {setTypeface(tf);return;}}switch (typefaceIndex) {case SANS:tf = Typeface.SANS_SERIF;break;case SERIF:tf = Typeface.SERIF;break;case MONOSPACE:tf = Typeface.MONOSPACE;break;}setTypeface(tf, styleIndex);}
从方法setTypefaceFromAttrs()看,如果你有set fontFamily属性,那么typefaceattribute将被忽略。
这边会发现这样设置typeface和fontFamily属性对中文不生效,这时候就需要引用外部的字体样式(这里谷歌设计规范推荐使用NOTO字体https://www.google.com/get/noto/)
2)使用字体样式文件设置(otf,ttf文件都可以)
在assets下新建一个fonts文件,把字体样式文件放进去
在代码中设置
AssetManager mgr = getAssets();
Typeface tf = Typeface.createFromAsset(mgr, "fonts/NotoSansCJKsc-Black.otf");
tv_1.setTypeface(tf);
2.批量设置字体样式
(1)自定义TextView
public class CustomTextView extends TextView
{public CustomTextView(Context context, AttributeSet attrs){super(context, attrs);}//重写设置字体方法@Overridepublic void setTypeface(Typeface tf){tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/NotoSansCJKsc-Light.otf");super.setTypeface(tf);}
}
之后在XML布局文件中使用CustomTextView代替TextView
<com.test.fontfamily.CustomTextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="6dp"android:text="自定义字体"android:textSize="24dp"/>
(2)更换整个App的字体
思路:遍历找到所有的TextView然后替换字体
百度了一下找到下面工具类
package com.test.fontfamily;import android.app.Application;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;/*** Created by Administrator on 2017/10/24.*/public class FontUtils
{private static final String TAG = FontUtils.class.getSimpleName();private Map<String, SoftReference<Typeface>> mCache = new HashMap<>();private static FontUtils sSingleton = null;public static Typeface DEFAULT = Typeface.DEFAULT;// disable instantiateprivate FontUtils(){}public static FontUtils getInstance(){// double checkif (sSingleton == null){synchronized (FontUtils.class){if (sSingleton == null){sSingleton = new FontUtils();}}}return sSingleton;}/*** <p>Replace the font of specified view and it's children</p>** @param root The root view.* @param fontPath font file path relative to 'assets' directory.*/public void replaceFontFromAsset(@NonNull View root, @NonNull String fontPath){replaceFont(root, createTypefaceFromAsset(root.getContext(), fontPath));}/*** <p>Replace the font of specified view and it's children</p>** @param root The root view.* @param fontPath font file path relative to 'assets' directory.* @param style One of {@link Typeface#NORMAL}, {@link Typeface#BOLD}, {@link Typeface#ITALIC}, {@link Typeface#BOLD_ITALIC}*/public void replaceFontFromAsset(@NonNull View root, @NonNull String fontPath, int style){replaceFont(root, createTypefaceFromAsset(root.getContext(), fontPath), style);}/*** <p>Replace the font of specified view and it's children</p>** @param root The root view.* @param fontPath The full path to the font data.*/public void replaceFontFromFile(@NonNull View root, @NonNull String fontPath){replaceFont(root, createTypefaceFromFile(fontPath));}/*** <p>Replace the font of specified view and it's children</p>** @param root The root view.* @param fontPath The full path to the font data.* @param style One of {@link Typeface#NORMAL}, {@link Typeface#BOLD}, {@link Typeface#ITALIC}, {@link Typeface#BOLD_ITALIC}*/public void replaceFontFromFile(@NonNull View root, @NonNull String fontPath, int style){replaceFont(root, createTypefaceFromFile(fontPath), style);}/*** <p>Replace the font of specified view and it's children with specified typeface</p>*/private void replaceFont(@NonNull View root, @NonNull Typeface typeface){if (root == null || typeface == null){return;}if (root instanceof TextView){ // If view is TextView or it's subclass, replace it's fontTextView textView = (TextView) root;// Extract previous style of TextViewint style = Typeface.NORMAL;if (textView.getTypeface() != null){style = textView.getTypeface().getStyle();}textView.setTypeface(typeface, style);} else if (root instanceof ViewGroup){ // If view is ViewGroup, apply this method on it's child viewsViewGroup viewGroup = (ViewGroup) root;for (int i = 0; i < viewGroup.getChildCount(); ++i){replaceFont(viewGroup.getChildAt(i), typeface);}} // else return}/*** <p>Replace the font of specified view and it's children with specified typeface and text style</p>** @param style One of {@link Typeface#NORMAL}, {@link Typeface#BOLD}, {@link Typeface#ITALIC}, {@link Typeface#BOLD_ITALIC}*/private void replaceFont(@NonNull View root, @NonNull Typeface typeface, int style){if (root == null || typeface == null){return;}if (style < 0 || style > 3){style = Typeface.NORMAL;}if (root instanceof TextView){ // If view is TextView or it's subclass, replace it's fontTextView textView = (TextView) root;textView.setTypeface(typeface, style);} else if (root instanceof ViewGroup){ // If view is ViewGroup, apply this method on it's child viewsViewGroup viewGroup = (ViewGroup) root;for (int i = 0; i < viewGroup.getChildCount(); ++i){replaceFont(viewGroup.getChildAt(i), typeface, style);}} // else return}/*** <p>Create a Typeface instance with specified font file</p>** @param fontPath font file path relative to 'assets' directory.* @return Return created typeface instance.*/private Typeface createTypefaceFromAsset(Context context, String fontPath){SoftReference<Typeface> typefaceRef = mCache.get(fontPath);Typeface typeface = null;if (typefaceRef == null || (typeface = typefaceRef.get()) == null){typeface = Typeface.createFromAsset(context.getAssets(), fontPath);typefaceRef = new SoftReference<>(typeface);mCache.put(fontPath, typefaceRef);}return typeface;}private Typeface createTypefaceFromFile(String fontPath){SoftReference<Typeface> typefaceRef = mCache.get(fontPath);Typeface typeface = null;if (typefaceRef == null || (typeface = typefaceRef.get()) == null){typeface = Typeface.createFromFile(fontPath);typefaceRef = new SoftReference<>(typeface);mCache.put(fontPath, typefaceRef);}return typeface;}/*** <p>Replace system default font. <b>Note:</b>you should also add code below to your app theme in styles.xml. </p>* {@code <item name="android:typeface">monospace</item>}* <p>The best place to call this method is {@link Application#onCreate()}, it will affect* whole app font.If you call this method after view is visible, you need to invalid the view to make it effective.</p>** @param context {@link Context Context}* @param fontPath font file path relative to 'assets' directory.*/public void replaceSystemDefaultFontFromAsset(@NonNull Context context, @NonNull String fontPath){replaceSystemDefaultFont(createTypefaceFromAsset(context, fontPath));}/*** <p>Replace system default font. <b>Note:</b>you should also add code below to your app theme in styles.xml. </p>* {@code <item name="android:typeface">monospace</item>}* <p>The best place to call this method is {@link Application#onCreate()}, it will affect* whole app font.If you call this method after view is visible, you need to invalid the view to make it effective.</p>** @param context {@link Context Context}* @param fontPath The full path to the font data.*/public void replaceSystemDefaultFontFromFile(@NonNull Context context, @NonNull String fontPath){replaceSystemDefaultFont(createTypefaceFromFile(fontPath));}/*** <p>Replace system default font. <b>Note:</b>you should also add code below to your app theme in styles.xml. </p>* {@code <item name="android:typeface">monospace</item>}* <p>The best place to call this method is {@link Application#onCreate()}, it will affect* whole app font.If you call this method after view is visible, you need to invalid the view to make it effective.</p>*/private void replaceSystemDefaultFont(@NonNull Typeface typeface){modifyObjectField(null, "MONOSPACE", typeface);}private void modifyObjectField(Object obj, String fieldName, Object value){try{Field defaultField = Typeface.class.getDeclaredField(fieldName);defaultField.setAccessible(true);defaultField.set(obj, value);} catch (NoSuchFieldException e){e.printStackTrace();} catch (IllegalAccessException e){e.printStackTrace();}}
}
阅读源码发现这里面主要方法有
replaceFont()
替换一个页面中的所有字体
用递归的方式去查找view是否是TextView或者TextView的子类,然后进行替换
不过这种方法效率不高
用法:
在页面中
FontUtils.getInstance().replaceFontFromAsset(View root, String fontPath)
modifyObjectField()
替换App所有字体
利用反射替换系统默认字体
用法:
a.新建一个BaseApplication继承Application在onCreate方法中
FontUtils.getInstance().replaceSystemDefaultFontFromAsset(this,"fonts/NotoSansCJKsc-Thin.otf");
b.在AppTheme中添加
<item name="android:typeface">monospace</item>
c.清单文件中使用BaseApplication
Android 修改字体样式,看这篇就够了相关推荐
- Android 控件 RecyclerView 看这篇就够了
[Android 控件 RecyclerView] 概述 RecyclerView是什么 从Android 5.0开始,谷歌公司推出了一个用于大量数据展示的新控件RecylerView,可以用来代替传 ...
- 关于Android 12 适配,看这篇就够了
一:功能和 API 概览 Android 12 面向开发者引入了一些出色的新功能和 API.以下几部分内容可帮助您了解适用于您的应用的功能并开始使用相关 API. 有关新增.修改和移除的 API 的详 ...
- Android原生TabLayout使用全解析,看这篇就够了
前言 为什么会有这篇文章呢,是因为之前关于TabLayout的使用陆陆续续也写了好几篇了,感觉比较分散,且不成体系,写这篇文章的目的就是希望能把各种效果的实现一次性讲齐,所以也有了标题的「看这篇就够了 ...
- html如何修改字体黑体,css如何修改字体样式?
css如何修改字体样式?比如黑体.宋体.微软雅黑.英文字体等字体如何设置?下面本篇文章给大家介绍一下使用css修改字体样式的方法.有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助. cs ...
- Android修改字体大小
Android修改字体大小 位置: File->Settings->IDE Settings->Editor->Colors & Fonts -> Font 也可 ...
- Android画中画模式-看这篇就够啦
最近做做播放器,有个浮窗播放的需求,两种实现方式,一种是申请浮窗权限,创建浮窗参考 flowWindow,一种是采用画中画模式(8.0以上) 关于画中画 Android 8.0 Oreo(API Le ...
- KDevelop修改字体样式和大小
(1)设置 -> 配置KDevelop (2)Editor -> 字体和颜色 -> 字体 -> 修改字体样式和大小 -> ok
- Android 设置字体样式
Android 设置字体样式 1.首先下载字体样式 我是在这里下载的字体样式http://www.zitixiazai.org/ 2.然后在下载好的字体样式放到assets项目文件下 接下来就是代码的 ...
- React入门看这篇就够了
2019独角兽企业重金招聘Python工程师标准>>> 摘要: 很多值得了解的细节. 原文:React入门看这篇就够了 作者:Random Fundebug经授权转载,版权归原作者所 ...
最新文章
- ResNet也能用在3D模型上了,清华「计图」团队新研究已开源
- zabbix3.0安装过程记录
- UIAlertController的使用及其自定义
- GitHub 发布重磅更新:你电脑上的 IDE 可以删了?!
- linux6 epel yum源,CentOS6下yum源与epel源配置
- http_build_query()就是将一个数组转换成url 问号?后面的参数字符串,并且会自动进行urlencode处理,及它的逆向函数...
- hibernate不能保存时分秒处理
- 安装cocos2D 2.1v 遇到的问题
- python简单绘图代码-python绘图代码
- 【thm】windows内网提权之Windows PrivEsc Arena
- 《深入浅出WPF》c#WPF入门,快速上手
- 用Python合并多个txt文件
- 计算机维护费可以跨年吗,税控技术维护费是否可以跨年抵扣?
- 互融云小额贷款系统开发:全流程管理的软件开发解决方案
- pencil替代产品哪个品牌更好?推荐平替pencil
- hadoop之求和和自定义排序编程
- cmsplus实战之仿[我扫网]之四:安装整站下载器并下载仿站所有数据
- sa 如何登录Sql Server
- 我的世界服务器怎么弄领地语言,我的世界领地指令大全 教你如何设置领地
- “芯片”三国之ARM篇:乱世枭雄曹孟德