views:

21

answers:

1

Is is possible to change TextView text after using Linkify to create links? I have something where I want the url to have two fields, a name and id, but then I just want the text to display the name.

So I start off with a textview with text that includes both name and id, and linkify to create the appropriate links with both fields. But for the display, I don't want to show the id.

Is this possible?

A: 

It's kind of a pain but yes. So Linkify basically does a few things. First it scans the contents of the textview for strings that match that of a url. Next it creates UrlSpan's and ForegroundColorSpan's for those sections that match it. Then it sets the MovementMethod of the TextView.

The important part here are the UrlSpan's. If you take your TextView and call getText(), notice it returns a CharSequence. It's most likely some sort of Spanned. From the Spanned you can ask, getSpans() and specifcally the UrlSpans. Once you know all those spans you can than loop through the list and find and replace the old span objects with your new span objects.

mTextView.setText(someString, TextView.BufferType.SPANNABLE);
if(Linkify.addLinks(mTextView, Linkify.ALL)) {
 //You can use a SpannableStringBuilder here if you are going to
 // manipulate the displayable text too. However if not this should be fine.
 Spannable spannable = (Spannable) mTextView.getText();
 // Now we go through all the urls that were setup and recreate them with
 // with the custom data on the url.
 UrlSpan[] spans = spannable.getSpans(0, spannable.length, UrlSpan.class);
 for (UrlSpan span : spans) {
   // If you do manipulate the displayable text, like by removing the id
   // from it or what not, be sure to keep track of the start and ends
   // because they will obviously change.
   // In which case you may have to update the ForegroundColorSpan's as well
   // depending on the flags used
   int start = spannable.getSpanStart(span);
   int stop = spannable.getSpanEnd(span);
   int flags = spannable.getSpanEnd(span);
   spannable.removeSpan(span);
   // Create your new real url with the parameter you want on it.
   UrlSpan myUrlSpan = new UrlSpan(Uri.parse(span.getUrl).addQueryParam("foo", "bar");
   spannable.setSpan(myUrlSpan, start, end, flags);
 }
 mTextView.setText(spannable);
}

Hopefully that makes sense. Linkify is just a nice tool to setup the correct Spans. Spans just get interpreted when rendering text.

Greg
thanks for the reply, that's very helpful. I didn't know what goes on "behind the scenes" when you use linkify.
jeanh