Search code examples
androidtextviewclickablespannablestring

How to make specific words' occurrences in a textview clickable


I need to make all the occurrences of a bunch of words, that I have in my textview text clickable

Eg. - I have 2 names in my arraylist - Ajay and Dhananjay and lets say text in my textview is ........

@Ajay, @Dhananjay, I just had a great fight with @Vijay yesterday

now, I need to highlight only @Ajay and @Dhananjay all occurences in my textview, and make them clickable as well but not @Vijay (as its not in my arraylist)

How to do so?


Solution

  • A few modifications in Survivor's Answer worked for me, as per my requirement.

      text = (TextView) findViewById(R.id.textView1);
    
      string += " ";
    
        SpannableString ss = new SpannableString(string);
        String[] words = string.split(" ");
        for (final String word : words) {
           if (word.startsWith("@") && mentionsNamesList.contains(word.substring(1))) {
                 int lastIndex = 0;
    
                while(lastIndex != -1){
    
                    lastIndex = string.indexOf(word+" ",lastIndex);
    
                    if(lastIndex != -1){
                ClickableSpan clickableSpan = new ClickableSpan() {
                    @Override
                    public void onClick(View textView) {
                        //use word here to make a decision
                    }
                };
              ss.setSpan(clickableSpan, lastIndex, lastIndex + word.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    
              lastIndex += word.length();
             }
            }
        }
        text.setText(ss);
        text.setMovementMethod(LinkMovementMethod.getInstance());
    

    The modifications done included the use of while loop in order to highlight and make clickable every occurrence of the word in the whole textview,instead of only the first one. The other one was adding space along with the word to highlight, in order to avoid highlighting the substring occurrence within a bigger word. For eg. test in test123