如何使用自定义字体设置 Spannable 对象字体
我有 Spannable 对象,我想通过之前加载的自定义字体来设置其字体。
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/font_Name.ttf");
Spannable span1 = /*Spannable Item*/;
/// I want to set span1 to have tf font face???
/// Here where I want help.
编辑:
我的问题是我想为文本视图设置两种不同的自定义字体,所以我正在使用 Spannable
I have Spannable object which I want to set its font by a custom font I have loaded before.
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/font_Name.ttf");
Spannable span1 = /*Spannable Item*/;
/// I want to set span1 to have tf font face???
/// Here where I want help.
EDIT :
My problem is that I want to set two different custom fonts for the text view so I am working with the Spannable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
这是一个迟到的答案,但将帮助其他人解决问题。
使用以下代码:(我使用孟加拉语和泰米尔语字体)
结果是:
CustomTypefaceSpan 类:
参考
This is a late answer but will help others to solve the issue.
Use the following code:(I'm using Bangla and Tamil font)
The outcome is:
CustomTypefaceSpan Class:
Reference
创建 CustomTypefaceSpan 类:
使用与 Android 框架跨类相同的方式:
此答案基于 Imran Rana 的答案,但不会扩展
TypefaceSpan
,然后禁用其功能。CustomTypefaceSpan
直接扩展MetricAffectingSpan
。这个答案与伊姆兰·拉纳的答案有一个缺陷。跨度没有被分割。即,如果您这样做(kotlin):
在
spannableStringBuilder
上设置的任何CustomTypefaceSpan
对象将不会被编组和解组。Create a CustomTypefaceSpan class:
Use in the same way as the Android framework spans classes:
This answer is based on Imran Rana's answer but does not extend
TypefaceSpan
and then disable its functionality.CustomTypefaceSpan
extendsMetricAffectingSpan
directly.This answer shares a defect with Imran Rana's answer. The span is not parcelled. I.e if you do this (kotlin):
Any
CustomTypefaceSpan
objects set onspannableStringBuilder
will not be marshalled and unmarshalled.我们不需要使用 CustomTypefaceSpan。这是使用 StyleSpan 的解决方案。
We don't need to use CustomTypefaceSpan. Here is the solution using StyleSpan.
如果您使用的是 Roboto,您可以在构造函数中设置不同的 TypefaceSpan
If you are using Roboto, you can set a different TypefaceSpan in the constructor
如果您使用的是 android KTX
buildSpannable{...}
,我推荐这个。
用法
If you are using android KTX
buildSpannable{...}
,I recommend this one.
Usage
>= API 28 的更新、更简单的答案
Newer, simpler answer for >= API 28
我想做同样的事情,但我发现我需要使用 TypefaceSpan。问题是采用 Typeface 的构造函数仅在 API 级别 28 中添加。因此我发现的解决方法是执行以下操作:
I wanted to do the same and I found that I need to use a TypefaceSpan. The problem is that the constructor taking a Typeface is only added in API level 28. So the workaround I found is to do the following:
在 kotlin 中是:
第一步,创建这个类
第二步,
In kotlin would be:
First step, create this class
Second step,
首先尝试将您的
Spannable
设置为您的TextView
,然后尝试使用myTextView.setTypeface(tf) 将字体分配给您的
;TextView
);Try to set your
Spannable
to yourTextView
first and then, try to assign the Typeface to yourTextView
withmyTextView.setTypeface(tf)
;这是一个示例,其中 str 是完整字符串,boldString 是需要加粗的部分。
Here is an example where, str is your full string and boldString is the part you need to make bold.