AutoCompleteTextView on "@" character typed Android

时间:2015-07-28 16:13:21

标签: android autocomplete android-edittext autocompletetextview social

I have a social messaging app that I am creating with a list of Strings of usernames and would like the edittext to show a list of the users when typing a message and keying in an "@".

How do I go about doing this?

1 个答案:

答案 0 :(得分:2)

您可以添加TextWatcher并动态更改AutoCompleteTextView的适配器。只更改数组并调用notifyDataSetChanged()似乎无法正常工作。

   autoCompleteView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                    int occurrences = 0;
                    String enteredString = s.toString();
                    for (char c : enteredString.toCharArray()) {
                        if (c == '@') {
                            occurrences++;
                        }
                    }
                    if (occurrences == 1) {
                        String requiredString = enteredString.substring(0, enteredString.indexOf("@"));
                        email[0] = requiredString + "@gmail.com";
                        email[1] = requiredString + "@hotmail.com";
                         .
                         .
                        email[10] = requiredString + "@yahoo.com";
                        adapter = null;
                        adapter = new ArrayAdapter<>(MyActivity.this, android.R.layout.simple_list_item_1, email);
                        autoCompleteView.showDropDown();
                        autoCompleteView.setThreshold(0);
                        autoCompleteView.setAdapter(adapter );
                    } else if (occurrences == 0) {
                        autoCompleteView.dismissDropDown();
                    }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

这是为了在输入时显示域列表&#39; @&#39; 。您可以修改代码以满足您的需求。