How to click or tap on a TextView text on different words?

I finally figured it out how to have multiple clickable parts in a TextView.
It is important that they all have their own ClickableSpan! That is where I went wrong the first time testing it. If they have the same ClickableSpan instance, only the last set span is remembered.

I created a String with the required clickable area’s surrounded by “[” and “]”.

String sentence = "this is [part 1] and [here another] and [another one]";

and here is the set TextView, the setMovementMehthod is also mandatory:

textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(addClickablePart(sentence), BufferType.SPANNABLE);

I have created this function, which will handle the creation of the clickable area’s:

private SpannableStringBuilder addClickablePart(String str) {
    SpannableStringBuilder ssb = new SpannableStringBuilder(str);

    int idx1 = str.indexOf("[");
    int idx2 = 0;
    while (idx1 != -1) {
        idx2 = str.indexOf("]", idx1) + 1;

        final String clickString = str.substring(idx1, idx2);
        ssb.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                Toast.makeText(getView().getContext(), clickString,
                        Toast.LENGTH_SHORT).show();
            }
        }, idx1, idx2, 0);
        idx1 = str.indexOf("[", idx2);
    }

    return ssb;
}

Leave a Comment