【问题标题】:Can't get HREF to work in Android strings.xml无法让 HREF 在 Android strings.xml 中工作
【发布时间】:2011-04-22 12:46:29
【问题描述】:

我正在尝试在“关于”框中添加指向 Twitter 个人资料的链接。电子邮件地址和网址等“常规”链接由

android:autoLink="email|web"

在 about.xml 中,但对于 Twitter 个人资料页面,我需要在我的 strings.xml 中使用 html 代码。我试过了:

<string name="twitter">Follow us on &lt;a href=\"http://www.twitter.com/mytwitterprofile"&gt;Twitter: @mytwitterprofile&lt;/a&gt;</string>

在 about 框上呈现 html 标记。

我也试过了:

<string name="twitter">Follow us on <a href="http://www.twitter.com/mytwitterprofile">Twitter: @mytwitterprofile</a></string>

显示文本“在 Twitter 上关注我们:@mytwitterprofile”,但它不是超链接。

我该怎么做这个看似简单的任务!?

干杯, 巴里

【问题讨论】:

  • 如何将字符串添加到您的盒子中?
  • 看看你是否觉得这篇文章有用 - stackoverflow.com/questions/1997328/…
  • TextView textView = (TextView) findViewById(R.id.about_content); textView.setTextColor(Color.WHITE); textView.setText(getString(R.string.about_text, getString(R.string.twitter), getString(R.string.email_address), getString(R.string.website)));

标签: android href


【解决方案1】:

问题是您的“a href”链接标签位于 strings.xml 中,并且在解析 strings.xml 时被解析为标签,这是您不想要的。这意味着您需要让它忽略使用 XML 的 CDATA 的标签:

&lt;string name="sampleText"&gt;Sample text &lt;![CDATA[&lt;a href="www.google.com"&gt;link1&lt;/a&gt;]]&gt;&lt;/string&gt;

然后您可以继续使用Html.fromHtml() 并使用LinkMovementMethod 使其可点击:

TextView tv = (TextView) findViewById(R.id.textHolder);
tv.setText(Html.fromHtml(getString(R.string.sampleText)));
tv.setMovementMethod(LinkMovementMethod.getInstance());

【讨论】:

  • 我认为关闭 CDATA 部分应该是 ]]> 而不仅仅是 ]]。 示例文本 link1]]>
【解决方案2】:

简单的答案是TextView 不支持&lt;a&gt; 标签。 AFAIK,它只支持基本格式,例如&lt;b&gt;&lt;i&gt;&lt;u&gt;。但是,如果您提供 android:autoLink="web",则以下字符串:

<string name="twitter">Follow us at twitter.com/mytwitterprofile</string>

twitter.com/mytwitterprofile 转换为正确的链接(当通过像android:text="@string/twitter" 这样的XML 设置时;如果您想从代码中设置它,您需要其他人在答案中发布的Html.fromHtml 方法)。

【讨论】:

  • 谢谢。这并不完美,但它会做到的。顺便说一句,我也不需要 Html.fromHtml (虽然我的 about.xml 有 android:autoLink="email|web")
【解决方案3】:

我不太确定如何使用“字符串”进行链接,但您可以使用 fromHtml 设置 EditText 或 TextView 的文本...

TextView text = (TextView) findViewById(R.id.text);
text.setText(Html.fromHtml("<a href=\"http://www.google.com\">Google Link!</a>"));
text.setMovementMethod(LinkMovementMethod.getInstance());

【讨论】:

  • 感谢您的回复,但这只是显示“Google 链接!”,而不是超链接。
  • text.setMovementMethod(LinkMovementMethod.getInstance());应该把它变成一个可点击的链接?!
  • 很遗憾不是,只是普通文本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 2015-10-18
相关资源
最近更新 更多