假设我有一个字符串
String str =" Hello, @John how's going on"
现在我想知道,如何突出显示单词 @John
并希望使其可从 Textview 中点击
最佳答案
您可以在 spannable
字符串中使用 clickable span
,如下所示:-
SpannableString ss = new SpannableString(" Hello, @John how's going on");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
//perform click operation
}
@Override
public void updateDrawState(TextPaint ds) {
}
};
ss.setSpan(clickableSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTv.setText(ss);
yourTv.setMovementMethod(LinkMovementMethod.getInstance());
yourTv.setHighlightColor(Color.TRANSPARENT);
startIndex - is the index of J of word John in the full string
endIndex - is the index of n of the word John in the full string.
&& 一旦 john 被点击,就会触发 onclick 方法..
编辑
要提取用户名 John,您可以拆分字符串并像下面的代码 fragment 一样获取它:-
String username = yourString.split("@")[1].split(" ")[0]; // this will extract john
关于java - 从 textView 中提取一部分文本并使该文本可点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972875/