Android开发之字体设置
2024-10-18 18:13:52
默认字体
Android SDK自带了四种字体:"normal"“monospace",“sans”, “serif”,如下:
字体
看这四兄弟长的还是蛮像,我是看不出多大差别。。。
设置方式
1.通过XML文件设置
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="monospace"
android:textSize="20dp"
android:textColor="#000000"
android:typeface="monospace"
android:layout_margin="5dp"/>
2.Java代码中设置
TextView txtNormal = (TextView) findViewById(R.id.txt_normal);
txtNormal.setTypeface(Typeface.MONOSPACE);
设置第三方字体
Res中使用
右键选择项目的app / res文件夹,然后选择New > Android resource directory。
image.png
Resource type中选择font,File name名为font。
image.png
将字体文件拷贝到font中
image.png
java代码中使用
TextView txtNormal = (TextView) findViewById(R.id.txt_helvetica);
Typeface typeface = ResourcesCompat.getFont(this, R.font.helvetica);
txtNormal.setTypeface(typeface);
Assets中使用
新建Assets及fonts目录,并将字体文件拷贝到fonts目录下
拷贝字体
在java代码中使用
TextView txtNormal = (TextView) findViewById(R.id.txt_helvetica);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf");
txtNormal.setTypeface(typeface);
第三方框架全局字体设置
这里推荐一个第三方字体设置库Calligraphy,详细可以点击连接
添加依赖
compile 'uk.co.chrisjenx:calligraphy:2.3.0'
新建Application
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Helvetica.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
}
}
在Activity中重写attachBaseContext方法
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
在xml中使用
<TextView
android:id="@+id/txt_helvetica"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lorem ipsum"
android:textSize="20dp"
android:textColor="#000000"
android:layout_margin="5dp"
fontPath="fonts/Helvetica.ttf"
tools:ignore="MissingPrefix"/>
如果fontPath="fonts/Helvetica.ttf"报错,在View上添加 tools:ignore="MissingPrefix”即可。
其他具体功能,详见Calligraphy
最新文章
- PHP读取Excel数据写入数据库(包含图片和文字)
- Kubuntu 使用YaH3C进行中大校园网认证
- UVa 10498 Happiness! (线性规划)
- IOS7 position:fixed 定位问题
- openstack之keystone
- Java文件中为什么只能有一个public修饰的类, 并且类名还必须与文件名相同
- redis安装(针对2.8以上版本)
- GC选择之串行收集与并行收集
- idea properties文件中文无法正常显示
- eclipse/idea远程调试Linux程序
- 1192:放苹果(dp + 搜索)
- 跨站请求伪造 CSRF
- Fiddler抓包域名过滤
- 2018.09.27 hdu5564Clarke and digits(数位dp+矩阵快速幂)
- Hihocoder之conv2d()
- 170704、springboot编程之CommandLineRunner
- 数学图形(2.15)Spherical sinusoid球面正弦曲线
- 快速排序算法-python实现
- 24_java之转换流和缓冲流
- 编写高质量代码改善C#程序的157个建议——建议126:用名词和名词组给类型命名
热门文章
- linux 下一些命令
- Educational Codeforces Round 62 (Rated for Div. 2) - C Playlist
- jdbc,mybatis,hibernate各自优缺点及区别
- DAY13、迭代器,生成器,枚举
- linux 实现centos7在线升级最新版本内核
- Linux 学习 (四) 帮助命令
- 使用Spring Boot Actuator将指标导出到InfluxDB和Prometheus
- centos7搭建gitlab服务器、汉化
- MySQL 无法启动,出现 “发生系统错误 1067。”
- Unity 阴影的制作方式