Friday, 28 February 2014

How to Create AutoComplete TextView in Android

main.xml

<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"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Auto Complete Text View"
        android:layout_gravity="center"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="#336633"
        android:layout_marginTop="20dp"/>

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="20dp"
        android:text="AutoCompleteTextView"
        android:layout_gravity="center" >

        <requestFocus />
    </AutoCompleteTextView>

</LinearLayout>

AutoCompleteTextViewActivity.java

package com.anju.tiwari.autocompletetextview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class AutoCompleteTextViewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    String str[]={"Ajay","Jay","Bholu","Anju","Rakesh","Bablu","Arjun","Jaydip","Raj","Sonu","Kaushal",
            "Bajarangi","Soni","Shreyance","Rinku","Umesh","Tiwari","Ujjwal","Tinku","Komal"};
   
    AutoCompleteTextView autoTv=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
    ArrayAdapter<String> adptr=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, str);
    autoTv.setThreshold(1);
    autoTv.setAdapter(adptr);
    }

  }








AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.anju.tiwari.autocompletetextview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:screenOrientation="portrait"
            android:name="com.anju.tiwari.autocompletetextview.AutoCompleteTextViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>