androidmultiautocompletetextview

How to show dropdown only when inserting @ character on MultiAutoCompleteTextView in android


I have a MultiAutoCompleteTextView. It works fine. But I want to show suggestion dropdown only when user type @ on it (like tagging user in facebook app). I have no idea how to do it. Here is my code :

mChatbox = (MultiAutoCompleteTextView) findViewById(R.id.chatbox);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, userList);
mChatBox.setAdapter(adapter);
mChatBox.setTokenizer(new SpaceTokenizer());

public class SpaceTokenizer implements MultiAutoCompleteTextView.Tokenizer {

public int findTokenStart(CharSequence text, int cursor) {
    int i = cursor;
    while (i > 0 && text.charAt(i - 1) != ' ') {
        i--;
    }
    while (i < cursor && text.charAt(i) == ' ') {
        i++;
    }
    return i;
}

public int findTokenEnd(CharSequence text, int cursor) {
    int i = cursor;
    int len = text.length();

    while (i < len) {
        if (text.charAt(i) == ' ') {
            return i;
        } else {
            i++;
        }
    }

    return len;
}

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 + " ";
        }
    }
}

Solution

  • I got a solution by myself. I create custom view which extends MultiAutoCompleteTextView and override performFiltering in it. Check if first char is "@", then filter the next chars after it. Otherwise, replace chars with "*" to avoid filtering. Here is my code.

    @Override
    protected void performFiltering(CharSequence text, int start, int end, int keyCode) {
        if (text.charAt(start) == '@') {
            start = start + 1;
        } else {
            text = text.subSequence(0, start);
            for (int i = start; i < end; i++) {
                   text = text + "*";
            }
        }
        super.performFiltering(text, start, end, keyCode);
    }