我想在文本中更改特定字符串的字体大小。 所以我使用这个代码来做到这一点,它适用于我的设备。但是当涉及到其他设备时,它出了问题,如图所示
我的代码
String[] arr = s.split("FAILED");
for ( String ss : arr) {
String s1 = arr[0];
String s2 = arr[1];
String s3 = "FAILED";
SpannableString span1 = new SpannableString(s3);
span1.setSpan(new AbsoluteSizeSpan(80),0, s3.length(), SPAN_INCLUSIVE_INCLUSIVE);
CharSequence finalText = TextUtils.concat(s1, " ", span1," ",s2);
tkt.setText(finalText);
}
相同的消息在两个不同的设备中显示不同的风格。我怎样才能纠正它?
答案 0 :(得分:1)
这是魔术。享受全世界最简单的方法;)
public void setHighLightedText(TextView tv, String textToHighlight) {
String tvt = tv.getText().toString();
int ofe = tvt.indexOf(textToHighlight, 0);
Spannable wordToSpan = new SpannableString(tv.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToHighlight, ofs);
if (ofe == -1)
break;
else {
wordToSpan.setSpan(new RelativeSizeSpan(2f), ofe,ofe + textToHighlight.length(), 0); // set size
wordToSpan.setSpan(new ForegroundColorSpan(Color.RED), ofe, ofe + textToHighlight.length(), 0);// set color
tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
}
}
}
将此方法称为
textView.setText("I love coding");
setHighLightedText(textView,"coding");