Home > Tutorials > Auto-link for TextView

Auto-link for TextView


In Android, auto-link for text doesn’t mean only for URL web addresses, but also for phone numbers, map addresses or emails.

Something like this:

Linkify (color default)

Linkify (color default)

The class Linkify is used to support every TextView or Spannable in auto-link these texts.

The sample code demonstrate the above image:

package pete.android.study;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.text.util.Linkify;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView tvDisplay = (TextView)findViewById(R.id.tvDisplay);
        String data = "" +
        "This is a sample of using Linkify to create auto-link to your text entry.\n" +
        "\n" +
        "URL: http://xjaphx.wordpress.com/ \n" +
        "Email: pete.houston.17187@gmail.com \n" +
        "Phone: (82)-10-9887-6231 \n" +
        "Address: 436 Mayfield Ave, Stanford, CA \n" +
        "\n" +
        "It's nice, isn't it?";

        if(tvDisplay != null) {
	        tvDisplay.setText(data);
	        Linkify.addLinks(tvDisplay, Linkify.ALL);
        }
    }
}

You can specify what kind of auto-link you want to create by these options: Linkify.EMAIL_ADDRESSES for email, Linkify.MAP_ADDRESSES for map address, Linkify.PHONE_NUMBERS for phone numbers, or all links by Linkify.ALL.

If you don’t want the default blue linking color, you can change its color through the TextView by using: setTextLinkColor().

Linkify (Yellow color)

Linkify (Yellow color)

tvDisplay.setLinkTextColor(Color.YELLOW);

That’s all! Hope you learn something from this.

Cheers,
Pete Houston

About these ads
Categories: Tutorials Tags: ,
  1. January 30, 2014 at 8:15 am | #1

    Thanks! Saved me some time.

  2. sagar
    January 25, 2013 at 10:16 am | #2

    awesme………….ty

  3. Bennie
    February 3, 2012 at 2:37 am | #3

    Exactly what I needed, thanks!

    I noticed a small, but important, typo: “you can change its color through the TextView by using: setTextLinkColor().” should read “setLinkTextColor()” (not TextLink).

    Cheers!

  4. November 16, 2011 at 5:32 pm | #5

    thanksssssssssss

  5. November 12, 2011 at 11:13 pm | #6

    Thank you :-)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: