Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating links in TextViews

I need to be able to create a link for a TextView in an app, but the actual URL to which the link will point needs to be added dynamically.

Through research here on SO, I found the following code:

        textView.setText(Html.fromHtml(
                    "<b>text3:</b>  Text with a " +
                    "<a href=\"http://www.google.com\">link</a> " +
                    "created in the Java source code using HTML."));
        textView.setMovementMethod(LinkMovementMethod.getInstance());

This allegedly will set a link in the TextView as it would in HTML. This is exactly what I need to do, but I need the URL to be dynamic, based on a string variable that would be passed to the setText(). How do I easily go about doing this?

To clarify: I want to display the word "website" is a link, and I need the URL to which that link directs to be dynamically updated based on the specific path that brought the user to that view.

Thanks!

EDIT: Here is the updated code:

String linkedText = "<b>text3:</b>  Text with a " +
            String.format("<a href=\"%s\">link</a> ", WEB) +
            "created in the Java source code using HTML.";
web.setText(Html.fromHtml(linkedText));

web.setMovementMethod(LinkMovementMethod.getInstance());

Here is the TextView's XML:

        <TextView
            android:id="@+id/vWeb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/vPhone"
            android:layout_marginTop="5dp"
            android:layout_toRightOf="@+id/webIcon"
            android:paddingLeft="1dp"
            android:autoLink="web"
            android:textIsSelectable="true" />
like image 954
user2163853 Avatar asked Jul 23 '13 01:07

user2163853


People also ask

What is LinkMovementMethod?

android.text.method.LinkMovementMethod. A movement method that traverses links in the text buffer and scrolls if necessary. Supports clicking on links with DPad Center or Enter.


1 Answers

If I understand the question correctly, you could try using String.format():

String dynamicUrl = "http://www.google.com"; // or whatever you want, it's dynamic

String linkedText = "<b>text3:</b>  Text with a " +
        String.format("<a href=\"%s\">link</a> ", dynamicUrl) +
        "created in the Java source code using HTML.";

textView.setText(Html.fromHtml(linkedText));
textView.setMovementMethod(LinkMovementMethod.getInstance());

Edit: You also need to remove android:autoLink="web" from the XML for this to work.

like image 153
Brian Avatar answered Nov 13 '22 02:11

Brian