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" />
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With