为什么 Spannable String 在不同的设备上表现不同?
why Spannable String behave differently on different devices?
我想更改文本中特定字符串的字体大小。
所以我使用这段代码来做到这一点,它对我的设备运行良好。但是当涉及到其他一些设备时就出错了,如图
我的代码
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);
}
相同的消息在两个不同的设备上以不同的样式显示。我该如何更正它?
这就是魔法。在全世界享受最简单的方法 ;)
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");
我想更改文本中特定字符串的字体大小。 所以我使用这段代码来做到这一点,它对我的设备运行良好。但是当涉及到其他一些设备时就出错了,如图
我的代码
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);
}
相同的消息在两个不同的设备上以不同的样式显示。我该如何更正它?
这就是魔法。在全世界享受最简单的方法 ;)
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");