In Auto Complete Text View whenever we start writing a text in the Edit View than it will automatically show the available optionsrelated to that text as you stored in an array or in a database.
In this example, I am storing the available options in the array and than just set the adapter for simple dropdown list available in android environment with that list.
To make this type of application you need to use theAutoCompleteTextView class available in android environment rather than simple TextView or EditView.
Let’s start coding by creating a project in Eclipse : File => New =>Android Application Project and give a package name ascom.javalanguageprogramming.autocompletetextdemo.
Copy the code for activity_main.xml as shown below :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<AutoCompleteTextView
android:id="@+id/autoText"
android:layout_width="220dp"
android:layout_height="50dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="50dp"
/>
</LinearLayout>
In this xml file I am using AutoCompleteTextView for completing of text automatically from String array.
Now consider the code for Main.java as shown below :
package com.javalanguageprogramming.autocompletetextdemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends Activity {
AutoCompleteTextView autoText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize auto complete text view
autoText = (AutoCompleteTextView)findViewById(R.id.autoText);
//make an array for the suggestions
String[] suggest = {"aa", "all", "auto", "ask", "bb", "bat", "bad", "back", "ball", "cat", "java", "Program", "tutorial"};
//make an array adapter for viewing string array
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, suggest);
//set the adapter to the auto complete text view
autoText.setAdapter(adapter);
}
}
In this Activity, a String array named as “suggest” is used to provide the available options and ArrayAdapter for providing the views to the drop down list