android - 如何使用 html 突出显示某些文本?
问题描述
工作完美,但是当我使用 html 突出显示文本时,某些文本无法完美查看(印地语文本)。
安卓
String str="रिश्ते भले ही कम ही बनाओ लेकिन दिल से निभाओ,\n" +
"क्योंकि आज कल इंसान अच्छाई के चक्कर में अच्छे खो देते है।";
//textview.setText(str);
textview.setText(Html.fromHtml(String.format(colorfulltext(str))), TextView.BufferType.SPANNABLE);
// highlight text
public String colorfulltext(String text) {
String[] colors = new String[]{"#fdc113", "#fdc113", "#fdc113","#fdc113", "#fdc113" ,"#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc", "#fcfcfc","#fcfcfc","#fcfcfc","#fcfcfc","#fcfcfc"};
StringBuilder finals = new StringBuilder();
int size = colors.length;
int k = 0;
for (int item = 0; item < text.length(); item++) {
if (k >= size) {
k = 0;
}
finals.append("<font color='" + colors[k] + "'>" + text.charAt(item) + "</font>");
k++;
}
return finals.toString();
}
解决方案
为什么要将 String 转换为 html 以将 fontcolor 应用于静态文本?
您必须按照以下步骤操作:
- 在 Strings.xml 中为每个文本创建条目。例如,रिश्ते 有不同的颜色,需要在 strings.xml 中作为单独的条目。
将此添加到 Util 类:
public static void addColoredPart(SpannableStringBuilder ssb, String word, int color,String... texts) { for(String text : texts) { if (word != null) { int idx1 = text.indexOf(word); if (idx1 == -1) { return; } int idx2 = idx1 + word.length(); ssb.setSpan(new ForegroundColorSpan(color), idx1, idx2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } }
通过以下方式应用样式:
String string1 = context.getString(R.string.String_id1) String string2 = context.getString(R.string.String_id2) SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); spannableStringBuilder.append(string2) spannableStringBuilder.append(string2) SpannableUtil.addColoredPart( spannableStringBuilder, spannableStringBuilder.toString(), color, string1, string2);
推荐阅读
- python-3.x - 将网页保存到文本文件时出现编码错误
- python - 有没有办法从它的一个属性中检索一个 python 对象?(Python)
- python - TCP 服务器未接收到所有发送的字节
- javascript - 作为 req.query 传递时带有井号 (#) 的文本在后端消失
- performance - 在 Julia 中更快地读取 CSV 文件
- r - R/sf:将多边形边界约束到重叠的多边形层
- excel - 如何遍历行数不同的每一行?
- c# - 如何从鼠标坐标中获得正确的像素位置?
- python - 碰撞检测在 pygame 中无法正常工作
- jmeter - 在 Load runner 中处理相关性并在 JMeter 中使用它们