16

I have an AutoCompleteTextView I use to select an item from a long list. The user should only be able to select a predetermined item from the list. They should not be able to enter their own item.

The way I check to make sure they submit only an item from the list is to use setOnItemClickListener to trigger a boolean flag. The problem is that after the boolean flag is set to true, they can still edit the selected text of the item. I need to detect this and set the boolean flag to false again. How do I do this. I have seen a suggestion to use onKeyDown, but I am not sure how to implement this.

Rynardt
  • 5,547
  • 7
  • 31
  • 43
  • Refer the below link https://stackoverflow.com/questions/7055534/how-to-avoid-getting-both-called-onitemclicked-and-ontextchanged-on-autocomplet – Jitheesh S Khan Oct 28 '18 at 04:02

3 Answers3

54

You can add text changed listener:

autoCompleteTextView.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {                

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});
maszter
  • 3,680
  • 6
  • 37
  • 53
  • 2
    How do you distinguish dropdown selection from replacing the whole string by the user with this solution ? – foo Feb 06 '17 at 21:50
  • 1
    I did this by searching the adapter for new string. My use case however is hooked up to an api and shows search results. So the issue for me was that when the text got updated after selecting a search result in the popup, the popup would appear again instead of disapear. – Jesson Atherton Oct 18 '18 at 08:27
  • @Jesson Atherton How did you sole this issue. Its like infinte loop for me – Jemsheer K D Nov 15 '18 at 15:11
1

Implement a TextWatcher, which will give you 3 methods which will constantly get call backs when someone changes the text. If the string grows, your user is typing by himself again.

TooCool
  • 10,598
  • 15
  • 60
  • 85
Stefan de Bruijn
  • 6,289
  • 2
  • 23
  • 31
0

Use

AutoCompleteTextView#setOnItemSelectedListener() 

- works like a charm.

J. Chomel
  • 8,193
  • 15
  • 41
  • 69
foo
  • 574
  • 8
  • 13
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – J. Chomel Feb 13 '17 at 12:54