Getting current suggestion from `AutoCompleteTextView`

后端 未结 2 404
忘了有多久
忘了有多久 2020-12-30 12:47

How do you get the current top suggestion in an AutoCompleteTextView? I have it suggesting items, and I have a text change listener registered. I also have a

相关标签:
2条回答
  • 2020-12-30 13:21

    AutoCompleteTextView does not scroll down to the best selection, but narrows down the selection as you type. Here is an example of it: http://developer.android.com/resources/tutorials/views/hello-autocomplete.html

    As I see it from AutoCompleteTextView there is no way to get current list of suggestions.

    The only way seem to be writing custom version of ArrayAdapter and pass it to AutoCompleteTextView.setAdapter(..). Here is the source to ArrayAdapter. You must only change a method in inner class ArrayFilter.performFiltering() so that it exposes FilterResults:

    .. add field to inner class ArrayFilter:

    public ArrayList<T> lastResults;  //add this line
    

    .. before end of method performFiltering:

      lastResults = (ArrayList<T>) results; // add this line
      return results;
    }
    

    Using it like this (adapted example from link):

    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
    CustomArrayAdapter<String> adapter = new CustomArrayAdapter<String>(this, R.layout.list_item, COUNTRIES);
    textView.setAdapter(adapter);
    
    // read suggestions
    ArrayList<String> suggestions = adapter.getFilter().lastResult;
    
    0 讨论(0)
  • 2020-12-30 13:37

    I've done what you want to do with the following code:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.autocomplete_1);
    
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, COUNTRIES);
        AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
        textView.setAdapter(adapter);
    
        adapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                Log.d(TAG, "dataset changed");
                Object item = adapter.getItem(0);
    
                Log.d(TAG, "item.toString "+ item.toString());
            }
        });
    }
    

    item.toString will print the text that is displayed on the first item.

    Note that this will happen even if you aren't showing the pop-up (suggestions) yet. Also, you should check if there are any items that passed the filter criteria (aka the user's input).

    To solve the first problem:

        int dropDownAnchor = textView.getDropDownAnchor();
        if(dropDownAnchor==0) {
            Log.d(TAG, "drop down id = 0"); // popup is not displayed
            return;
        }
        //do stuff
    

    To solve the second problem, use getCount > 0

    0 讨论(0)
提交回复
热议问题