androidautocompletetextview

Android AutocompleteTextview Inline predictions


I am trying to implement a AutocompleteTextview very similar to the Autocomplete of google in my Android app.

I got all the predictions working but I still miss one feature. I want that the first prediction of the dropdown will be displayed in the EditText of the AutocompleteTextview. Also I want that the item is selected when the user clicks on return (or Tab) like google does it in the browser.

Is there a way to do this with the AutocompleteTextview of Android?


Solution

  • As I cannot figure out a way to get the current suggestions list from "outside" the Adapter extension, I'd do the following:

    Disclaimer: I've never tried something like this nor I have the resources to try it right now, angry boss danger.

    Assuming you are extending an Adapter which has an inner filter that makes the filtering process, you should have overriden the publishResults() method. My tip is: declare a class-wide variable of type String that when publishResults() is called, also sets it to the first of the FilterResults strings:

    @Override
    protected void publishResults(final CharSequence constraint, final FilterResults results) {
      currentObjects = (List<T>) results.values;
      
      if (results.count > 0) {
        myFirstSuggestion = currentObjects.toString();
        notifyDataSetChanged();
      }
      else
        notifyDataSetInvalidated();
    }
    

    Additionally, make a new method called getFirstSuggestion() that would return this myFirstSuggestion string.

    So now: how to trigger it? Seems that AutoCompleteTextView already has this listener implemented:

    onFilterComplete(int count)

    Notifies the end of a filtering operation.

    So basically the steps to go would be:

    1. Declare this listener over your AutoCompleteTextView

    2. Inside, use the following shippet to get the first suggestion:

      AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.your_actv_id);
      ListAdapter adapter = actv.getAdapter();
      String firstSuggestion = adapter.getFirstSuggestion();
      
    3. actv.setHint(firstSuggestion);

    For your second question, you'd need to override the onEditorAction method, something like this

    actv.OnEditorActionListener enter = new actv.OnEditorActionListener() {
      public boolean onEditorAction(AutoCompleteTextView view, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_GO) {
          ListAdapter adapter = view.getAdapter();
          String firstSuggestion = adapter.getFirstSuggestion();
          view.setHint(firstSuggestion);
        }
        return true;
      }
    };
    

    The disclaimer is valid for this latter too, probably if my former idea works, this will also.