How to create AutoComplete text view in Android Application
In this tutorial, we will learn how to create Auto complete text view. In this example I am using hard corded value, in real world these value can be fetched from DB, RSS feed or from some other sources.
- Create new Android project.
- Add autotext view layout in main.xml file as shown below -
< ?xml version="1.0" encoding="utf-8"?>
< LinearLayout
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
< AutoCompleteTextView
android:id="@+id/textAutoComplete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:layout_marginLeft="20dp"
android:text=""
android:textSize="18sp" />
< /LinearLayout>
- Now need to attach the adapter to this auto complete view in activity class. I am using hard coded string array for demo purpose -
package com.test.autocompletetest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class AutoCompleteTest extends Activity {
private String[] sports = { "Cricket", "Football", "Table tenis", "Hockey", "Others" };
AutoCompleteTextView acTextView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter adapter =
new ArrayAdapter
(this,android.R.layout.simple_dropdown_item_1line, sports);
acTextView = (AutoCompleteTextView)findViewById(R.id.textAutoComplete);
//Assigning the threshold value for auto complete view, so here once
//user type one character then all the items from the adapter matching
//that character will be displayed.
acTextView.setThreshold(1);
//Assigning the adapter to auto complete view.
acTextView.setAdapter(adapter);
}
}
- Run the application and you will see the auto complete text view will be populated with matching to your first character which you type.
No comments:
Post a Comment