Search code examples
javaandroidautocompletetextviewtagging

How to implement the auto-suggest UI using Android Studio?


I am writing the photos app. The user can click on a person's photo and tag it. I want to implement the tagging as follows:

  • 1) The user looks at the photo and recognizes John Smith.
  • 2) The user clicks on the text input field.
  • 3) The user starts typing 'Jo...'
  • 4) A list of suggested gmail accounts appears for the user to choose from (e.g. johny123@gmail.com, johnsmith@gmail.com, joanna@gmail.com).
  • 5) The user clicks on the correct account (johnsmith@gmail.com) in the list.
  • 6) The photo is tagged with the account the user has chosen.

I have implemented many parts except for the 4th. Below I present the code for the current UI:

// This method is invoked after the user finishes typing and clicks enter.
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
    // other code
    ...

    String usersEntry = textView.getText().toString();
    tagPhotoWith(usersLabel);
    return true;
}

Currently whatever text the user types becomes the photo tag after the user clicks enter. Instead, I want the app to show the list of suggested gmail.com accounts so that the user could select the appropriate account for tagging. How to do that?


Solution

  • You have to use a AutoCompleteTextView to get suggestions for saved strings(as in your case, they are Email-IDs, whether fetched from database or pre-defined in the program at some time).

    Here, an adapter is set over the AutoCompleteTextView to get string array/Arraylist set for the input box as soon as user types 2 or 3 characters of the string.

    AutoCompleteTextView textProductView;
    textProductView = (AutoCompleteTextView) findViewById(R.id.txtItem);
    
    ArrayAdapter<String> etAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, ITEMS);
    textProductView.setAdapter(etAdapter);
    

    Here, ITEMS is a string array defined as per data fetched from user/database or predefined in activity.