我正在尝试制作一个内置本地化的应用程序,但我想要一种可以在文本中创建 Web 链接的方法,该 URL 在其他地方定义(以便于维护)。
因此,我在 res/values/strings.xml 中有我的链接:
<?xml version="1.0" encoding="utf-8"?>
<resources>
...
<string name="link1">http://some.link.com</string>
<string name="link2">http://some.link2.com</string>
</resources>
和我在 res/values-en-rGB/strings.xml 中的本地化文本
<?xml version="1.0" encoding="utf-8"?>
<resources>
...
<string name="sampleText">Sample text\nMore text and link1\nMore text and link2.</string>
</resources>
我没有测试过这个位,但是来自 localization section of developer.android.com它说这种减少内容重复的方法应该有效,尽管我不确定我应该把意大利语放在哪个文件夹中。它会在“res/values-it-rIT/strings.xml”中吗?让我们假设我也有其他各种语言。
我正在寻找一种获取基本本地化“sampleText”并将我的 html 链接插入其中并在单击时让它们工作的方法。到目前为止,我已经尝试了两种方法:
1,
在“sampleText”(%s)中添加一些格式:
<string name="sampleText">Sample text\nMore text and <a href="%s">link1</a>\nMore text and <a href="%s">link2</a>.</string>
然后像这样处理文本:
TextView tv = (TextView) findViewById(R.id.textHolder);
tv.setText(getResources().getString(R.string.sampleText, getResources().getString(R.string.link1), getResources().getString(R.string.link2)));
但是当我点击链接时这不起作用,即使链接文本被放置在正确的位置。
2,我尝试使用 Linkify,但正则表达式路径可能很困难,因为我正在考虑支持非拉丁语言。我试图在链接文本周围放置一个自定义 xml 标记,然后执行如下操作:
Pattern wordMatcher = Pattern.compile("<span1>.*</span1>");
String viewURL = "content://" + getResources().getString(R.string.someLink);
Linkify.addLinks(tv, wordMatcher , viewURL );
但这也不起作用。
所以,我想知道是否有一种方法可以将多个 URL 动态添加到将链接到 Web 内容的同一文本的不同部分?
最佳答案
问题是您的“a href”链接标签在 strings.xml
内并在 strings.xml
时被解析为标签被解析,这是你不想要的。这意味着您需要让它忽略使用 XML 的 CDATA 的标签:
<string name="sampleText">Sample text <![CDATA[<a href="http://www.google.com">link1</a>]]></string>
然后你可以继续 Html.fromHtml()
并使用 LinkMovementMethod
使其可点击:
TextView tv = (TextView) findViewById(R.id.textHolder);
tv.setText(Html.fromHtml(getString(R.string.sampleText)));
tv.setMovementMethod(LinkMovementMethod.getInstance());
关于android - 动态设置指向 strings.xml 中文本的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2244194/