为什么Spannable String在不同的设备上表现不同?

时间:2018-04-14 08:18:17

标签: android spannablestring

我想在文本中更改特定字符串的字体大小。 所以我使用这个代码来做到这一点,它适用于我的设备。但是当涉及到其他设备时,它出了问题,如图所示

我的代码

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);

        }

enter image description here

enter image description here

相同的消息在两个不同的设备中显示不同的风格。我怎样才能纠正它?

1 个答案:

答案 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");