Android UI How to - Use TextView autoLink








If you know that the content of the TextView is going to contain a URL or an e-mail address, you can set the autoLink property to email|web, and the TextView will highlight any e-mail addresses and URLs.

When the user clicks on one of these highlighted items, the system will take care of launching the e-mail application with the e-mail address, or a browser with the URL.

In XML, this attribute would be inside the TextView tag and would look something like this:

<TextView ...     
          android:autoLink="email|web"
          ...
/>

You specify a pipe-delimited set of values including web, email, phone, or map, or use none (the default) or all.

To set autoLink behavior in code instead of using XML, the corresponding method call is setAutoLinkMask().

You would pass it an int representing the combination of values sort of like before, such as android.text.util.Linkify.EMAIL_ADDRESSES|Linkify.WEB_ADDRESSES.

TextView tv =(TextView)this.findViewById(R.id.tv);
tv.setAutoLinkMask(Linkify.ALL);
tv.setText("Please visit my website, http://www.java2s.com or email me at info@java2s.com.");

You have to set the auto-link options on TextView before setting the text. Setting the auto-link options after setting the text won't affect the existing text.





Example

The following is the xml layout file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//  w w  w .j a va  2  s  . com
    <TextView
        android:id="@+id/myEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="abc@yourserver.com"
        android:autoLink="email" />

</LinearLayout>

Java code

package com.java2s.app;
/*  www  . j  a  va2 s.  c  o  m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}
null