Auto Complete feature is a great feature for applications that involve fields that have to be filled manually. In Android the AutoCompleteTextView brings this feature. This is a relatively simple control to use and a fully functional auto complete feature can be implemented in just 4 lines of code.
Here is what we are going to do:
Here is what we are going to do:
- Define the AutoCompleteTextView in XML (or Java).
- Create a ArrayAdapter for the AutoCompleteTextView.
- Set the adapter you created in step 2 to the AutoCompleteTextView.
- Set the threshold value for the AutoCompleteTextView. The threshold value defines the number of characters that has to be typed before the auto complete list is displayed on the screen.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<AutoCompleteTextView
android:id="@+id/autocomplete_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
package com.mobsandgeeks.acd;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends Activity {
private static final String[] FRUITS = {
"Apple", "Orange", "Banana", "Avacado", "Pear",
"Peach", "Lemon", "Pineapple", "Strawberry", "Gooseberry",
"Grapes", "Watermelon", "Mango", "Papaya", "Dragonfruit",
"Guava", "Honeydew", "Jackfruit", "Kiwifruit", "Olive",
"Pomegranate", "Raspberry", "Fig", "Custard Apple"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autocomplete_textview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, FRUITS);
actv.setThreshold(1);
actv.setAdapter(adapter);
}
}
Source Code
You can download the source code from here.
Screenshot
No comments:
Post a Comment