How to make a link INSIDE a string resource (along

2020-03-08 05:53发布

问题:

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?

回答1:

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.