I have an AutoCompleteTextView
in my app which works. I have successfully created an onClickItemListener
. The question is how to grab the text the user selected.
And this is the thing: I have an ArrayList
with words being passed to the Adapter
to search for suggestions. As the user types a word the suggestions list gets shorter (in rows on the UI side) so when i want to get the word from the ArrayList
at the index the user selected i get the wrong word because the indexes doesn't match.
How can I get the text (String
) the user chose without having to mess with the index?
Here's my code:
public class AutocompleteActivity extends BaseActivity { private DBManager m_db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.autocomplete); m_db = new DBManager(this); final ArrayList<String> words = m_db.selectAllWords(); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, words); AutoCompleteTextView tv = (AutoCompleteTextView)findViewById(R.id.autocomplete); tv.setThreshold(1); tv.setAdapter(adapter); tv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Log.i("SELECTED TEXT WAS------->", words.get(arg2)); } }); } }
If you want to get suggestions , when you type in an editable text field , you can do this via AutoCompleteTextView. It provides suggestions automatically when the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.
Just call your adapter. getItem(position) and you will get the output you want. For example skillLevelAdapter. getItem(position).
In android, we can create an AutoCompleteTextView control in two ways either manually in an XML file or create it in the Activity file programmatically. First we create a new project by following the below steps: Click on File, then New => New Project. After that include the Kotlin support and click on next.
Yeah... unfortunately the name of the parameters on the onItemClick method you must implement are not so self-descriptive but here is an example with the names of what they are:
autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) { String selection = (String)parent.getItemAtPosition(position); //TODO Do something with the selected text } });
For more info see: http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
arg0
being your AdapterView
and arg2
the position.
Have you tried:
arg0.getItemAtPosition(arg2);
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