Saturday, May 23, 2015

How to add a hyperlink programmatically in a TextView in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="@android:color/white"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sample TextView..."
        android:padding="15dp"
        android:textSize="25dp"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Put A HyperLink On TextView"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.method.LinkMovementMethod;

public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final TextView tv = (TextView) findViewById(R.id.tv);
        Button btn = (Button) findViewById(R.id.btn);

        // Set a click listener for Button widget
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                    Spanned
                    This is the interface for text that has markup objects attached to ranges of it.
                 */

                Spanned html = Html.fromHtml("Click the link to visit <br />" +
                        "<a href='https://www.google.com/'>Google.com</a>");

                /*
                    setMovementMethod(MovementMethod movement)
                        Sets the movement method (arrow key handler) to be used for this TextView.

                    LinkMovementMethod
                        A movement method that traverses links in the text buffer and
                        scrolls if necessary. Supports clicking on links with
                        DPad Center or Enter.
                 */
                tv.setMovementMethod(LinkMovementMethod.getInstance());

                // Set TextView text from html
                tv.setText(html);
            }
        });
    }
}
More android examples