Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a link INSIDE a string resource (along with other text in it) ? - Android

For example: Take a look at the following string resource:

 <string name="b1b">This link will take you to google.com. More text here.</string>

Now I want this string resource to look like this in my app:

This link will take you to Google. More text here.

I can't use three textviews. This was just an example. So I can't make the entire textview a link.

(Why? What I'm doing in my app is … I have say a dozen buttons, each of them sends a string resource ID as an intent to a "Text Shower Activity" … and in that I simply have a single textview which shows different texts based on which button the user clicked. So, I'm saving on app size.

Plus every such text string resource has different number of links at different places, so it's not feasible to have a single textview just for links and somehow weave it in between.)

So, I need to make a little bit of the string resource into a link. I've tried the <a> thing with no effect.

How to do this?

like image 579
Zenis Avatar asked Oct 31 '25 10:10

Zenis


2 Answers

Example XML resource:

</string name="mlink">
    to go to Google<![CDATA[ <a href="http://google.com">click here</a>]]> 
    and <![CDATA[<a href="http://yahoo.com">this</a>]]> moves you to yahoo!
</string>

Java:

yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
yourTextView.setText(Html.fromHtml(getString(R.string.mlink)));

Note that you need to put your html link inside the CDATA tag, this is the proper way to use links in String resources.

like image 172
Droidman Avatar answered Nov 02 '25 23:11

Droidman


Just to add on @Droidman's answer if anyone wants to use it without CDATA, Below will also work without CDATA but we have to escaped the characters such as "<" , using the &lt; notation.

</string name="mlink">
to go to Google &lt;a href=\"http://google.com\"&gt;click here&lt;/a&gt; 
and &lt;a href=\"http://yahoo.com\"&gt;this&lt;/a&gt; moves you to yahoo!
</string>

Java:

yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
yourTextView.setText(Html.fromHtml(getString(R.string.mlink)));
like image 24
Nainal Avatar answered Nov 03 '25 00:11

Nainal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!