String sentence="this is @part 1 and #here another and #another one @user #newone @itsme ";
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(addClickablePart(sentence), BufferType.SPANNABLE);
private SpannableStringBuilder addClickablePart(String str) {
SpannableStringBuilder ssb=new SpannableStringBuilder(str);
int idx1=Math.min(str.indexOf("@"),str.indexOf("#") );
int idx2=0;
while (idx1!=-1) {
idx2=str.indexOf(" ", idx1) + 1;
final String clickString=str.substring(idx1, idx2);
ssb.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(), clickString,
Toast.LENGTH_SHORT).show();
}
}, idx1, idx2, 0);
idx1=Math.min(str.indexOf("#", idx2),str.indexOf("@", idx2) );
}
return ssb;
}
它的前五个字工作正常,但留下了最后一个(@itsme)。它只剩下最后一个(无论字符串的长度是多少)。