1

I have a chatroom Android app that I am making and I have a list of users that I would like to be autocompleted in the text view when there is an "@" typed.

So when a user types @ I would like a drop down of the users in the room to appear but only once the @ is typed.

How do I do this? Any solution would help, even not using an AutoCompleteTextView

hakobob
  • 81
  • 7

1 Answers1

1

What you're looking for is a MultiAutocompleteTextView: http://developer.android.com/reference/android/widget/MultiAutoCompleteTextView.html

Here's a Tokenizer I used for the same purpose. I use a custom Span to denote a profile tag called ProfileTagSpan, which is necessary because I need to display the profile name to the user but save the profile ID in the string. Yours could be simpler if this is not necessary.

public class ProfileTagTokenizer implements MultiAutoCompleteTextView.Tokenizer {

    /*
     * Search back from cursor position looking for @ symbol
     * If none found then cancel filtering by making the constraint length 0
     * Also cancel if another tag found as tags can't overlap
     */
    public int findTokenStart(CharSequence text, int cursor) {
        for (int i = cursor; i > 0; i--) {
            if (text.charAt(i - 1) == '@') return i;
            else if (text instanceof Spanned &&
                    ((Spanned) text).getSpans(i, i, ProfileTagSpan.class).length > 0) break;
        }
        return cursor;
    }


    /*
     * Use the cursor position for token end as we have no delimiter on the tag
     */
    public int findTokenEnd(CharSequence text, int cursor) {
        return cursor;
    }

    /*
     * Add a space after the tag
     */
    public CharSequence terminateToken(CharSequence text) {
        int i = text.length();
        while (i > 0 && text.charAt(i - 1) == ' ')
            i--;
        if (i > 0 && text.charAt(i - 1) == ' ') {
            return text;
        }
        else {
            if (text instanceof Spanned) {
                SpannableString sp = new SpannableString(text + " ");
                TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
                        Object.class, sp, 0);
                return sp;
            }
            else {
                return text + " ";
            }
        }
    }
}
darnmason
  • 2,672
  • 1
  • 17
  • 23
  • WOAH! That's confusing. So I have a list of strings; userList and a MultiAutocompleteTextView: editComplete... How do I do what I was trying to, I don't need anything like IDs... just when you click @ for the list of users to pop up – hakobob Jan 25 '15 at 22:07
  • The only difference between this and an AutocompleteTextView is the Tokenizer. It defines where a token starts and ends so that the widget knows when to show the popup and what to pass to the adapter as a filter. Are you familiar with standard AutocompleteTextViews and adapters? Is it just the tokenizer that you find confusing? – darnmason Jan 27 '15 at 00:35