How to convert SpannedString to Spannable

Kaidul picture Kaidul · Jul 26, 2013 · Viewed 14.9k times · Source

Hello I have set some text in a textview.

TextView tweet = (TextView) vi.findViewById(R.id.text);
tweet.setText(Html.fromHtml(sb.toString()));

Then I need to convert the text of the TextView into Spannble. So I did this like:

Spannable s = (Spannable) tweet.getText();

I need to convert it Spannable because I passed the TextView into a function:

    private void stripUnderlines(TextView textView) {
            Spannable s = (Spannable) textView.getText();
            URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
            for (URLSpan span : spans) {
                int start = s.getSpanStart(span);
                int end = s.getSpanEnd(span);
                s.removeSpan(span);
                span = new URLSpanNoUnderline(span.getURL());
                s.setSpan(span, start, end, 0);
            }
            textView.setText(s);
        }

private class URLSpanNoUnderline extends URLSpan {
        public URLSpanNoUnderline(String url) {
            super(url);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    }

This shows no error/warning. But throwing a Runtime Error:

java.lang.ClassCastException: android.text.SpannedString cannot be cast to android.text.Spannable

How can I convert the SpannedStringt/text of the textview into Spannble? Or can I do the same task with SpannedString inside the function?

Answer

CommonsWare picture CommonsWare · Jul 26, 2013

How can I convert the SpannedStringt/text of the textview into Spannble?

new SpannableString(textView.getText()) should work.

Or can I do the same task with SpannedString inside the function?

Sorry, but removeSpan() and setSpan() are methods on the Spannable interface, and SpannedString does not implement Spannable.