I have provided an AutoCompleteTextView
to show suggestions to the user. Based on the item selected by the user, I am getting the ID of the item and using it in data base side. Now my problem is to force the user to make selection only from AutoCompleteTextView
(i.e. user should not enter his own text). It is a client requirement. How to do this?
Here's a pretty straightforward solution:
You can create a variable to store the selected value by setting setOnItemClickListener
in your AutoCompleteTextView
. Then you can null
that value whenever a user types in the field by adding a TextWatcher
to it. Finally, you can validate your variable is not null before continuing.
String my_var; //keep track! AutoCompleteTextView tv = (AutoCompleteTextView) layout.findViewById(R.id.tv); tv.setAdapter(my_adapter); tv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { my_var = my_adapter.getItem(position).toString(); } }); /** * Unset the var whenever the user types. Validation will * then fail. This is how we enforce selecting from the list. */ tv.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) { my_var = null; } @Override public void afterTextChanged(Editable s) {} });
I happened to need such a requirement for a project I am working on, and I though I'll share you guys the way I implemented the required.
I added a on focus change listener for the auto-complete text view and checked when the user has focus changed focus from the auto-complete, and handled the situation straight forward.
autoTextViewCountry.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if(!b) { // on focus off String str = autoTextViewCountry.getText().toString(); ListAdapter listAdapter = autoTextViewCountry.getAdapter(); for(int i = 0; i < listAdapter.getCount(); i++) { String temp = listAdapter.getItem(i).toString(); if(str.compareTo(temp) == 0) { return; } } autoTextViewCountry.setText(""); } } });
So my implementation is: if the typed text doesn't exist in the array adapter then on focus changed empty the text view, and later on when continuing to next stage of say registration, check if this text view is empty or not.
Hope this approach helps somebody.
Happy coding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With