Wednesday, February 14, 2018

android kotlin - AutoCompleteTextView example

AutoCompleteTextView
The AutoCompleteTextView is an editable text view. The AutoCompleteTextView shows completion suggestions automatically while the app user is typing. The AutoCompleteTextView’s list of suggestions is displayed in a drop-down menu. The android app users can choose an item from the suggestions to replace the content of the edit box with.

The android app users can dismiss the AutoCompleteTextView suggestions drop-down menu any time by pressing the back key, or if no item is selected in the drop-down, by pressing the enter key.

So, from where did the AutoCompleteTextView suggestions are coming from? The AutoCompleteTextView suggestions list is obtained from a data adapter. The AutoCompleteTextView suggestions appear only after a given number of characters defined by the ‘threshold’.

So, how we implemented the AutoCompleteTextView in our tutorial? At first, we create an array of String values. Then we create an instance of ArrayAdapter with this array. Next, we bind this ArrayAdapter instance with the AutoCompleteTextView. So our AutoCompleteTextView shows the suggestions from the array values. After it, we define a threshold value for the AutoCompletetextView.

The important event is the AutoCompleteTextView item click listener. Using the onItemClickListener we hide the soft keyboard programmatically. We also get the user-selected suggestion programmatically in real time. We also can show the selected item in a toast message. Finally, we set a dismiss listener for the AutoCompleteTextView widget. When the suggestions drop-down menu is dismissed we display a toast message.

This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to see how we use an AutoCompleteTextView widget in an android application.

And how we show the suggestions for the AutoCompleteTextView and handle the user selection in this android application. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
MainActivity.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout


class MainActivity : AppCompatActivity() {
    private lateinit var context: Context
    private lateinit var autoCompleteTextView: AutoCompleteTextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the context
        context = this;

        // Get the widgets reference from XML layout
        val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
        autoCompleteTextView = findViewById(R.id.autoCompleteTextView)

        // Initialize a new array with elements
        val colors = arrayOf(
            "Azure", "Aqua", "Amber", "Red",
            "Green", "Blue", "Maroon", "Magenta",
            "Gold", "GreenYellow","Ghost white"
        )

        // Initialize a new array adapter object
        val adapter = ArrayAdapter<String>(
            this, // Context
            android.R.layout.simple_dropdown_item_1line, // Layout
            colors // Array
        )

        // Set the AutoCompleteTextView adapter
        autoCompleteTextView.setAdapter(adapter)

        // Auto complete threshold
        // The minimum number of characters to type to show the drop down
        autoCompleteTextView.threshold = 1

        // Set an item click listener for auto complete text view
        autoCompleteTextView.onItemClickListener = AdapterView
            .OnItemClickListener{
                parent,view,position,id->
                val selectedItem = parent.getItemAtPosition(position)
                    .toString()
                // Display the clicked item using toast
                showToast("Selected : $selectedItem")
                // Hide soft keyboard
                hideSoftKeyboard()
        }

        // Set a dismiss listener for auto complete text view
        autoCompleteTextView.setOnDismissListener {
            showToast("Suggestion closed.")
        }

        // Hide soft keyboard on root layout click
        rootLayout.setOnClickListener {
            hideSoftKeyboard()
            autoCompleteTextView.clearFocus()
        }
    }

    // Function to show toast message
    private fun showToast(message:String){
        Toast.makeText(context,message,Toast.LENGTH_SHORT).show()
    }

    // Function to hide soft keyboard programmatically
    private fun hideSoftKeyboard(){
        (getSystemService(
            INPUT_METHOD_SERVICE) as InputMethodManager
                ).apply {
            hideSoftInputFromWindow(currentFocus?.windowToken, 0)
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    android:background="#F8F8F8">

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="textNoSuggestions"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android examples