Creating Interactive Hyperlinks in Android TextViews

Implementing URL Navigation via TextView

1. Layout Declaration

Add a text element within the XML layout resource.

<TextView
    android:id="@+id/hyperlinkView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorLink="#1E90FF"
    android:text="Browse our official portal" />

2. Constructing the Spannable Object

Instantiate a SpannableString and attach a ClickableSpan to the targeted substring. This approach bypasses the need for a separate onClickListener on the view itself.

TextView hyperlinkView = findViewById(R.id.hyperlinkView);
SpannableString configuredText = new SpannableString("Browse our official portal");

ClickableSpan webNavigationSpan = new ClickableSpan() {
    @Override
    public void onClick(View widget) {
        String targetUrl = "https://www.example.com";
        Uri parsedUri = Uri.parse(targetUrl);
        Intent browserLaunch = new Intent(Intent.ACTION_VIEW, parsedUri);
        startActivity(browserLaunch);
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setUnderlineText(true);
    }
};

configuredText.setSpan(webNavigationSpan, 0, configuredText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
hyperlinkView.setText(configuredText);

3. Enabling Click Interaction

To ensure the span responds to touch events, the LinkMovementMethod must be assigned to the TextView.

hyperlinkView.setMovementMethod(LinkMovementMethod.getInstance());

Tags: Android TextView ClickableSpan SpannableString UI Development

Posted on Fri, 07 Aug 2026 16:36:14 +0000 by Jibberish