Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Multiple ClickableSpan in a TextView

I've been stuck at this problem for long. What I'm having is a simple string "This is a link and this is another link". I want to have both "link" words click-able, having different URLs to open in browser.

  • The simplest way I can do is to set Click-able Span on both "link" words with different URLs, but the problem I'm facing is finding the start and end positions of the span. The text is dynamic, and I have to programmatically find the positions.
  • One approach would be to find the first occurrence of the word 'link', find the start and end positions and set the span, and then the second occurrence. But that is not reliable. The text may contain more than one kind of repeated words, like "This is a cat link and this is another cat link". Here I have to link both "cat" and "link" words with different URLs via Click-able Span. How do I go about it?
like image 310
Avi Singh Avatar asked Feb 18 '15 07:02

Avi Singh


1 Answers

Try in this manner

String s="Cat link 1 Cat link 2 Cat link 3";
    SpannableString ss = new SpannableString(s);
    String first ="Cat link 1";
    String second ="Cat link 2";
    String third ="Cat link 3";
    int firstIndex = s.toString().indexOf(first);
    int secondIndex = s.toString().indexOf(second);
    ClickableSpan firstwordClick = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            ///............
        }
    }; 
    ClickableSpan secondwordClick = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            ///............
        }
    }; 
    ss.setSpan(firstwordClick,firstIndex, firstIndex+first.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(secondwordClick,secondIndex, secondIndex+second.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setLinksClickable(true);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(ss,BufferType.SPANNABLE);
like image 143
Fahim Avatar answered Oct 01 '22 07:10

Fahim