开发者

URLSpan in SpannableString

I am following this example in using Sp开发者_运维知识库annableString: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/text/Link.html

I am trying to create a string which has 'R.string.text1' following by R.string.text2 but R.string.text2 (has 10 characters) in URL format:

SpannableString ss = new SpannableString(getString(R.string.text1));
ss.setSpan(new URLSpan(getString(R.string.text2)), 0, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

But what I am getting is

  1. I don't see the string R.string.text2 at all
  2. and only the first 10 characters is in URL format

How can I fix my problem?


This is a more general answer to show just a basic working example of a URLSpan.

URLSpan in SpannableString

// 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 


May i correct you ?

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);

quite late, but at least done for the others ^^

you can also do it this way :

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;


try this way..

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);


In the kotlin, you can use like this way

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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜