2

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!

Darko Petkovski
  • 3,892
  • 13
  • 53
  • 117

1 Answers1

12

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());
vipul mittal
  • 17,343
  • 3
  • 41
  • 44
  • thanks @vipul and to get the clicked word you can use this inside onClick : Spanned sp = (Spanned) ((TextView)textView).getText(); int start = sp.getSpanStart(this); int end = sp.getSpanEnd(this); String word = sp.subSequence(start, end).toString(); – Hoby Aug 09 '17 at 04:36
  • 3
    `SpannableString` doesn't have `split` and `indexOf` methods – user924 Oct 27 '17 at 19:46