Android AutoCompleteTextView Kotlin

06-Dec-2024

Implement AutoCompleteTextView in Android studio project using Kotlin

AutoCompleteTextView is an Android widget  that provides suggestions as the user types.


Here is the tutorial for Java




This is often used to allow users to quickly select items from a list of suggestions.
Here is an example of using AutoCompleteTextView in an Android app:


There Are Some Common Attributes for AutoCompleteTextView:


id
This is unique identity.
layout_widthmatch_parent -> Text area contains fullscreen
wrap_content-> Text area contains only text size
layout_widthmatch_parent -> Text area contains fullscreen
wrap_content-> Text area contains only text size
textSize
Change The Text Size
textColor
Change Text Color
drawableLeft
Set Icon in Left
drawableRightSet Icon in Right
drawableTopSet Icon in Top
drawableBotomSet Icon in Botom
textStyle
bold, italic, normal -> Style Change
background
Set background Color



File open res/layout/activity_main.xml file −



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">


<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_margin="20dp"
android:orientation="vertical">


<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="text here" />
</LinearLayout>



</RelativeLayout>


File open com.microappvalley.newtestproject/MainActivity.kt file −



package com.microappvalley.newtestproject

import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
var fruits = arrayOf("Apple", "Banana", "Jackfruit", "Mango")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val autoCompleteTextView: AutoCompleteTextView =findViewById(R.id.autoCompleteTextView)

val adpter:ArrayAdapter<String> = ArrayAdapter(this@MainActivity,android.R.layout.simple_dropdown_item_1line,fruits)
autoCompleteTextView.threshold = 1
autoCompleteTextView.setAdapter(adpter)
}
}


Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.


Output:



Comments