Search code examples
androidhtmlurltextview

Android TextView html added url not working


I'm developing an app in Java with targetSdkVersion set to 30. I have an activity where I need to display to a user a clickable URL in form of click me with the long URL hidden within supporting HTML.

I'm struggling for some time. Currently my code works as below

            if (station.getSponsorUrl().length() > 32) {
                stationSponsorUrl.setClickable(true);
                stationSponsorUrl.setMovementMethod(LinkMovementMethod.getInstance());
                stationSponsorUrl.setText(Html.fromHtml("<a href=\"" + station.getSponsorUrl() +"\">" + getString(R.string.www_link) + "</a>\n", HtmlCompat.FROM_HTML_MODE_LEGACY));
            }
            else {
                stationSponsorUrl.setText(station.getSponsorUrl());
            }

When I remove a call to setMovementMethod the URL renders correctly (font color) but it is not clickable at all. When I leave setMovementMethod active it is not even displayed as a URL. I see the text defined by R.string.www_link in the unchanged format. Of course it is also not working.

else case works correctly and when I set the TV content with plain HTML link it works out of the box. The tv is defined in XML layout as below

                    <TextView
                        android:id="@+id/textViewSponsorUrl"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="24dp"
                        android:autoLink="all"
                        android:fontFamily="@font/alegreya_sans_sc_medium"
                        android:linksClickable="true"
                        android:text="TextView"
                        android:textSize="18sp"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />

Solution

  • You are running into trouble using android:autoLink="all" in your layout. I suggest that you delete that autolink line and adjust your code as follows:

    stationSponsorUrl.setMovementMethod(LinkMovementMethod.getInstance());
    String anchorText;
    if (station.getSponsorUrl().length() > 32) {
        anchorText = getString(R.string.www_link)
    } else {
        anchorText = station.getSponsorUrl()
    }
    stationSponsorUrl.setMovementMethod(LinkMovementMethod.getInstance());
    stationSponsorUrl.setText(
        HtmlCompat.fromHtml(
            "<a href=\"" + station.getSponsorUrl() + "\">" + anchorText + "</a>\n", HtmlCompat.FROM_HTML_MODE_LEGACY
        )
    );
    

    You could also turn autolink off for long URLs using setAutoLinkMask():

    stationSponsorUrl.setAutoLinkMask(0)