![]() |
VOOZH | about |
Android AutoCompleteTextView is an advanced EditText which shows a list of suggestions when user starts typing text. When the user starts typing, a drop-down menu appears, showing a list of relevant suggestions based on the user input. The user can then select an item from the list.
The AutoCompleteTextView is a subclass of EditText class so we can easily inherit all the properties of EditText as per our requirements. The dropdown list will be obtained using the data adaptor and these suggestions appears only after entering the minimum number of characters defined in the Threshold limit. The Threshold limit is used to define the minimum number of characters the user must type to see the dropdown list of suggestions. 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.
In this article, we will learn how to add a AutoCompleteTextView programmatically using Kotlin.
First we create a new project by following the below steps:
In this file, we only use the LinearLayout and set it attributes.
activity_main.xml:
First of all, we declare two variables autotextview and button to create the widgets and set their attributes.
val autoCompleteTextView = AutoCompleteTextView(this)
val button = MaterialButton(this)
and add both autoCompleteTextView and button in LinearLayout using
val linearLayout: LinearLayout = findViewById(R.id.main)
linearLayout.addView(autoCompleteTextView)
linearLayout.addView(button)
then, we declare another variable languages to get the items of the string-array from the strings.xml file.
val languages = listOf("Java", "Kotlin", "Swift", "Python", "Scala", "Perl", "Javascript", "Jquery")Create an adaptor and add into the AutoCompleteTextView of LinearLayout using
adapter = ArrayAdapter(
this, android.R.layout.simple_list_item_1, languages
)
MainActivity.kt: