Android Html.fromHtml支持特殊字体(自定义任
2022-07-19 本文已影响0人
寻水的鱼Chock
预览效果
image.png功能说明
- 支持自定义HTML TAG,默认
<kfont>...</kfont>
; - 支持color属性,与原生
<font color='#FF0000'></font>
TAG一致; - 支持size属性,扩展原生的
<font size='12ps'>...</font>
,支持单位dp/sp/px; - 支持face属性,扩展原生的
<font face='monospace'></font>
,支持任意字体;
使用方式
在工程根目录的build.gradle中添加
allprojects {
repositories {
maven { url 'https://www.jitpack.io' }
...
}
}
添加依赖
implementation 'com.gitee.chockqiu:html-font-face:1.0'
使用示例
TextView tvHtml = findViewById(R.id.tvHtml);
TextView tvHtml2 = findViewById(R.id.tvHtml2);
TextView tvHtml3 = findViewById(R.id.tvHtml3);
HtmlTagRegister reg = new HtmlTagRegister();
HtmlFontFaceHandler fontFace = new HtmlFontFaceHandler("kfont") {
@Override
public Typeface onNeedFontFace(String faceName) {
if (faceName.equalsIgnoreCase("DIN")) {
return Typeface.createFromAsset(getAssets(),
"DIN_Alternate_Bold.ttf"
);
} else if (faceName.equalsIgnoreCase("YouSheBiaoTiHei")) {
return Typeface.createFromAsset(getAssets(),
"YouSheBiaoTiHei.ttf"
);
}
return null;
}
};
reg.registerHtmlTag(fontFace);
tvHtml.setText(Html.fromHtml("<kfont color='#FF0000' size='16px'>愿有前程可奔赴,1234567890</kfont>", null, reg));
tvHtml2.setText(Html.fromHtml("<kfont color='#0000FF' face='DIN' size='16dp'>亦有岁月可回首,1234567890</kfont>", null, reg));
tvHtml3.setText(Html.fromHtml("<kfont color='#00FF00' face='YouSheBiaoTiHei' size='18sp'>且有情深共白头。1234567890</kfont>", null, reg));