如何使用AutoCompleteTextView android实现callout

时间:2014-11-27 20:51:32

标签: android autocompletetextview

如何在Android中使用AutoCompleteTextView实现@callout。我希望在我在facebook这样的文本框中键入@时显示建议列表。

1 个答案:

答案 0 :(得分:0)

只需添加一个带有AutoCompleteTextView.addTextChangedListener的TextWatcher并实现afterTextChanged来获取@,如果你发现它只是更新了autocompelete的适配器。

样品:

final AutoCompleteTextView tx = (AutoCompleteTextView)findViewById(R.id.text);
    tx.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) {

            // get previous "@" or space
            String sub = s.toString().substring(0, start + count);

            if(sub.isEmpty())
                return;

            int index = -1;

            for( int i = start + count - 1; i >= 0; --i){
                if(sub.charAt(i) == '@') {
                    index = i;
                    break;
                }else if(sub.charAt(i) == ' '){
                    break;
                }
            }

            // No @ found before a space or the start of the string
            if(index == -1)
                return;

            String valueToSearch = s.toString().substring(index + 1, start + count);

            tx.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, /*filtered results with valueToSearch*/));
            tx.showDropDown();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });