Background
Everyone must have used EditText to allow use input some text. Ever wondered if such a basic functionality could support autocomplete? Of course it would, it is one of the basic use cases. We will see how to implement it in this post.
AutoCompleteTextView
AutoCompleteTextView is a direct subclass of EditText. We can use this to achieve auto complete feature in Android.
Let's start with the layout. I am going to keep it fairly simple. Just a label denoting what the following text field is for. In this case it would be list of countries. So we are going to provide auto complete for list of countries.
<RelativeLayout 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"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/labelId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="@string/autocomplete_label"/>
<AutoCompleteTextView
android:id="@+id/autocompleteId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/labelId"/>
</RelativeLayout>
Layout would look something like
Before we proceed to the Java code/Activity lets quickly define list of countries as string array in string resource file.
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">AutocompleteDemo</string> <string name="title_activity_main">Auto Complete Demo</string> <string name="autocomplete_label">List of Countries</string> <string-array name="list_of_countries"> <item>India</item> <item>USA</item> <item>China</item> <item>Canada</item> <item>Germany</item> <item>France</item> <item>Spain</item> <item>Japan</item> </string-array> </resources>
Have listed some random country name. That should suffice for this demo. Now lets code the Activity class.
package com.osfg.autocompletedemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
/**
* @author athakur
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.autocompleteId);
String[] countriesList = getResources().getStringArray(R.array.list_of_countries);
ArrayAdapter countryAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,countriesList);
acTextView.setAdapter(countryAdapter);
}
}




No comments:
Post a Comment