android: 使用 <a href> 设置链接在文本视图中 [英] android: Set link with <a href> in TextView
问题描述
我动态创建了一个 TextView 并希望将文本设置为可链接.文本值为Google".我提到了互联网&博客 像这样, 显示相同的方式,但我不能不会产生预期的结果.
I create a TextView dynamically and want to set the text as linkable. Text value is "Google". I referred to internet & blogs like this, which shows the same way, but I couldn't produce the expected results.
我尝试了不同的方法,但我看到的输出是整个文本,只有文本.我试过的代码是:
I tried different ways, but the output I see is the whole text with text only. The code I have tried with is :
TextView tv1 = new TextView(this);
tv1.setLayoutParams(textOutLayoutParams);
// Make Linkable
tv1.setMovementMethod(LinkMovementMethod.getInstance());
tv1.setText(Html.fromHtml(l.getLeftString()));
/*SpannableString s = new SpannableString(l.getLeftString());
Linkify.addLinks(s, Linkify.WEB_URLS);
tv1.setText(s);
tv1.setMovementMethod(LinkMovementMethod.getInstance());
*/
dialogLayout.addView(tv1);
在我的输出中,我看到Google"但没有链接.我也试过 Clean project &再次构建它,但没有成功.我希望只看到带有蓝色下划线的Google"(默认情况下),点击 Google 时,浏览器会打开 http://google.com.
In my output I see "Google" and no link. I also tried Clean project & building it again, but no success. I am looking to see only "Google" as underlined with blue color (as default) and on clicking Google, the browser open with http://google.com.
我的代码缺少什么来获得输出?顺便说一句,对于 REF:我使用 64 位 Win 7、Java、Eclipse、Android API 8-2.2
What is lacking in my code to get the output ? BTW For REF : I use 64bit Win 7, Java, Eclipse, Android API 8-2.2
非常感谢任何帮助.
推荐答案
我终于使用以下代码让它工作了:
I finally got it working using the following code :
TextView tv1 = new TextView(this);
tv1.setLayoutParams(textOutLayoutParams);
tv1.setText(Html.fromHtml("<a href=""+ l.getRightString() + "">" + l.getLeftString() + "</a>"));
tv1.setClickable(true);
tv1.setMovementMethod (LinkMovementMethod.getInstance());
dialogLayout.addView(tv1);
l.getRightString() - 包含类似 http:www.google.com 的网址l.getLeftString() - 包含 url 的文本,如Go to Google"
l.getRightString() - contains a url like http:www.google.com l.getLeftString() - contains text for the url like "Go to Google"
结果:在我的对话框中用蓝色和下划线输入Go to Google"文本,点击它,浏览器会打开并显示相应的页面.在返回/退出浏览器时,它再次从离开的状态返回到应用程序.
RESULTS : Text "Go to Google" on my dialog with blue color and underlined, and on clicking it the browser opens up and shwows the respective page. On returning/Exiting the browser it again comes to the app from the state where it had left.
希望这会有所帮助.
这篇关于android: 使用 <a href> 设置链接在文本视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!