我在使用SpannableString
时遵循此示例:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/text/Link.html
我正在尝试创建一个字符串,其中包含“R.string.text1”,后面是R.string.text2,但是R.string.text2(有10个字符)的URL格式:
SpannableString ss = new SpannableString(getString(R.string.text1));
ss.setSpan(new URLSpan(getString(R.string.text2)), 0, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
但我得到的是
如何解决问题?
答案 0 :(得分:5)
这是一个更为通用的答案,仅显示URLSpan
的基本工作示例。
// set up spanned string with url
SpannableString spannableString = new SpannableString("Click here for more.");
String url = "https://developer.android.com";
spannableString.setSpan(new URLSpan(url), 6, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// set to textview
textView.setText(spannableString);
textView.setMovementMethod(LinkMovementMethod.getInstance()); // enable clicking on url span
答案 1 :(得分:2)
我可以纠正你吗?
SpannableString ss = new SpannableString(getText(R.string.text1)+" "+getText(R.string.text2));
ss.setSpan(new URLSpan(getString(R.string.text2)),
getString(R.string.text1).length()+1,
ss.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
很晚,但至少为其他人做了^^
你也可以这样做:
SpannableString ss1 = new SpannableString(getText(R.string.text1));
// do what you want with ss1
SpannableString ss2 = new SpannableString(getText(R.string.text2)); // the text visible
ss2.setSpan(new URLSpan(getString(R.string.text2)), // this is the link itself
0,
ss2.length(), // link on entire text
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
CharSequence csSS = TextUtils.concat(ss1, ss2); // import android.text.TextUtils;
答案 2 :(得分:1)
试试这个..
SpannableString ss = new SpannableString(getString(R.string.text1+""+R.string.text2));
ss.setSpan(new URLSpan(getString(R.string.text2)), 0, getString(R.string.text2).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
答案 3 :(得分:0)
在Kotlin中,您可以像这样使用
fun SpannableStringBuilder.urlSpan(value: String): SpannableStringBuilder {
val start = length
this.append(value)
val end = length
this.setSpan(URLSpan(value), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
return this
}
SpannableStringBuilder().urlSpan("www.google.com")