Android: Make your TextView look like a hyperlink

0 Comments

There's no shortage of posts regarding Linkify and automatically making part of the TextView clickable. Just search for "android textview hyperlink" and you'll get a fair idea.

1.TextView tvMessage = (TextView) findViewById(R.id.txtMsg);
2.tvMessage.setAutoLinkMask(Linkify.ALL);

And the result would be something like...

image

But when you don't want the text to include http:// is when you'll have to look elsewhere.

image

To get this, it's really simple. You can even make a quick TextView subclass out of it.

01./**
02.  * Sets a hyperlink style to the textview.
03.  */
04.public static void makeTextViewHyperlink(TextView tv) {
05.  SpannableStringBuilder ssb = new SpannableStringBuilder();
06.  ssb.append(tv.getText());
07.  ssb.setSpan(new URLSpan("#"), 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
08.  tv.setText(ssb, TextView.BufferType.SPANNABLE);
09.}

And to set up the click handler, just use an ordinary OnClickListener so you can handle the click any way you want.

01.TextView tv = (TextView) findViewById(R.id.linkRecipes);
02.Utils.makeTextViewHyperlink(tv);
03.tv.setOnClickListener(new OnClickListener() {
04.  @Override
05.  public void onClick(View v) {
06.    Intent intent = new Intent(getApplicationContext(), RecipeActivity.class);
07.    startActivity(intent);
08.  }
09.});

ibEtB0r2aWAFJ
Done, like a BOSS!

While you're at it, check out my Diablo II Runewords app!

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog