Android 动态设置到strings.xml中文本的链接
我正在尝试制作一个内置本地化功能的应用程序,但我希望有一种方法可以在文本中创建一个web链接,URL可以在其他地方定义(便于维护) 因此,我在res/values/strings.xml中有我的链接:Android 动态设置到strings.xml中文本的链接,android,text,dynamic,localization,hyperlink,Android,Text,Dynamic,Localization,Hyperlink,我正在尝试制作一个内置本地化功能的应用程序,但我希望有一种方法可以在文本中创建一个web链接,URL可以在其他地方定义(便于维护) 因此,我在res/values/strings.xml中有我的链接: <?xml version="1.0" encoding="utf-8"?> <resources> ... <string name="link1">http://some.link.com</string> <string
<?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>
但是,当我点击链接时,这不起作用,即使链接文本被放在正确的位置
2,我尝试使用Linkify,但正则表达式路径可能很困难,因为我正在考虑支持非拉丁语言。我尝试在链接文本周围放置一个自定义xml标记,然后执行如下操作:
TextView tv = (TextView) findViewById(R.id.textHolder);
tv.setText(getResources().getString(R.string.sampleText, getResources().getString(R.string.link1), getResources().getString(R.string.link2)));
Pattern wordMatcher = Pattern.compile("<span1>.*</span1>");
String viewURL = "content://" + getResources().getString(R.string.someLink);
Linkify.addLinks(tv, wordMatcher , viewURL );
Pattern-wordMatcher=Pattern.compile(“.”);
String viewURL=“content://”+getResources().getString(R.String.someLink);
addLinks(电视、文字匹配器、viewURL);
但这也不起作用
因此,我想知道是否有一种方法可以动态地将多个URL添加到同一文本的不同部分,从而链接到web内容?尝试使用
Html.fromHtml()
将Html转换为Spannable
,然后放入TextView
。根据#1中的内容,我希望TextView
显示HTML源代码,而不是呈现的HTML。您必须实现
setMovementMethod(LinkMovementMethod.getInstance());
在您的文本视图上
下面是一个更好的例子:
问题是您的“a href”链接标记位于strings.xml
中,并且在解析strings.xml
时被解析为标记,这是您不希望看到的。这意味着您需要让它使用XML的CDATA忽略标记:
示例文本
然后您可以继续使用Html.fromHtml()
,并使用LinkMovementMethod
使其可单击:
TextView tv = (TextView) findViewById(R.id.textHolder);
tv.setText(Html.fromHtml(getString(R.string.sampleText)));
tv.setMovementMethod(LinkMovementMethod.getInstance());
在布局集中,android:autoLink到
web
<TextView android:text="@string/text_with_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="web" />
在strings.xml中,只需添加URL
http://stackoverflow.com/ FTW!
对于来自#1的示例文本,我尝试了以下方法:tv.setText(Html.fromHtml(getResources().getString(R.string.sampleText,getResources().getString(R.string.someLink),getResources().getString(R.string.someLink2)),TextView.BufferType.Spanable);但仍然无法获得可点击的链接。我是否在布局中遗漏了一些内容,或者遗漏了其他内容?这可能会起作用,然后CharSequence str=getResources().getText(R.string.sampleText);我不能让它工作。它只是显示超链接,不可点击。别忘了网址中的http://否则我会收到“找不到可处理意图的活动”错误谢谢!最干净的答案!未记录字符串资源以支持任意HTML标记。是
,
和
。我不建议依赖其他任何东西,例如
,在所有Android版本和设备上工作。也许您可以将@dule的答案标记为正确答案:)
TextView tv = (TextView) findViewById(R.id.textHolder);
tv.setText(Html.fromHtml(getString(R.string.sampleText)));
tv.setMovementMethod(LinkMovementMethod.getInstance());
<TextView android:text="@string/text_with_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="web" />
<string name="text_with_url">http://stackoverflow.com/ FTW!</string>