0

My app need such scenario like in a textView I stored "@dev will goto home and @Roy will go to Station. I want to open a dialer activity to call the clicked person.

But using this code if I click on any @words it shows whole string. am toasted string.

User can enter his own string and may be he/she enter or not the @contact and there is not defined index of the same.

multiAutoCompleteTextView.setText(addClickablePart(desc), TextView.BufferType.SPANNABLE);
private SpannableString addClickablePart(String str) {
    SpannableString ss = new SpannableString(str);
    Pattern pattern = Pattern.compile("[@]\\w*");
    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View textView) {
                // do toasting

                TextView b = (TextView)textView;
                String buttonText = b.getText().toString();
                Toast.makeText(ViewNote.this,buttonText,Toast.LENGTH_SHORT).show();
            }
        };
        ss.setSpan(clickableSpan, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return ss;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Devendra Singh
  • 2,343
  • 4
  • 26
  • 47

1 Answers1

0

You need to store the text which is associated with each ClickableSpan. Try something like this:

public static class ClickableSegmentSpan extends ClickableSpan {

        private String segment;

        public ClickableSegmentSpan(String segment) {
            this.segment = segment;
        }

        @Override
        public void onClick(View widget) {
            Toast.makeText(widget.getContext(), segment, Toast.LENGTH_SHORT).show();
        }
    }

The addClickablePart method would change to this:

private SpannableString addClickablePart(String str) {
        SpannableString ss = new SpannableString(str);
        Pattern pattern = Pattern.compile("[@]\\w*");
        Matcher matcher = pattern.matcher(str);

        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(new ClickableSegmentSpan(str.substring(start, end)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return ss;
    }
Samuil Yanovski
  • 2,837
  • 17
  • 19