Clickable words inside of TextView Android [duplic

2019-02-19 21:09发布

问题:

This question already has an answer here:

  • Create clickable link in text view in android 2 answers

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