Clickable words inside of TextView Android [duplicate]
Asked Answered
S

1

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!

Specify answered 18/8, 2014 at 12:27 Comment(0)
D
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());
Diantha answered 18/8, 2014 at 12:36 Comment(2)
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();Milburn
SpannableString doesn't have split and indexOf methodsRhiannonrhianon

© 2022 - 2024 — McMap. All rights reserved.