Spannable text is too wide for TextView

家住魔仙堡 提交于 2020-02-04 07:31:31

问题


I have a TextView with the font sans-serif-light. To link some words inside, I set a text as a Spannable like this:

final Spannable text = new SpannableString(textView.getText());
final Matcher matcher = PATTERN_TAG.matcher(text);
while (matcher.find()) {
    text.setSpan(span, startIndex, endIndex, 0);
}
textView.setText(text);
textView.setMovementMethod(LinkMovementMethod.getInstance());

The Span that I apply sets the word's font to sans-serif-medium like this:

public abstract class ClickableTagSpan extends ClickableSpan {

    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
    }
}

The problem is that the text becomes too wide for the TextView in some rows since the width of the medium font is larger than the light font that was orginally set. The TextView simply cuts off the text on the right edge. How can I get the TextView to respect the correct width of the text?


回答1:


Solved it by setting an additional TypefaceSpan, rather than modifying the ClickableSpan.

text.setSpan(clickableSpan, startIndex, endIndex, 0);
text.setSpan(new TypefaceSpan("sans-serif-medium"), startIndex, endIndex, 0);

This makes the TextView correctly wrap the text.



来源:https://stackoverflow.com/questions/31441422/spannable-text-is-too-wide-for-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!