问题
I have a textview that contains hashtags ex. #first #second #third
. My question is how can I detect which hashtag is clicked so I can perform some action - eg. make toast of the word.
Is this possible using TextView widget? Should I use some other widget istead?
UPDATE
I found my solution using this example. Hope it will help others in the future!
回答1:
You can use spannable string to achieve this:
SpannableString ss = new SpannableString("Your string");
String[] words = ss.split(" ");
for(final String word : words){
if(word.startsWith("#")){
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
//use word here to make a decision
}
};
ss.setSpan(clickableSpan, ss.indexOf(word), ss.indexOf(word) + word.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
TextView textView = (TextView) findViewById(R.id.hello);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
来源:https://stackoverflow.com/questions/25363310/clickable-words-inside-of-textview-android