Saturday, 28 January 2017

AutoCompleteTextView in Android

Today We are going to learn about AutoCompleteTextView in android. As the name suggest, it will do something automatically. Yes! It will show the data you are looking for by learning the first letter you have typed as you see in Google search box. So, Let's not make it a boring lecture, we will start coding for this.


Create a project in your Android Studio/Eclipse. I will suggest you to use Android Studio as it is faster and efficient than eclipse.

Lets suppose you have an xml file with name activity_main.xml and activity file with name MainActivity.java.

After you successfully created  a project, add below XML code in your activity_main.xml file.

 <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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.autocompletehandling.MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="8dp" >

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" >

            <AutoCompleteTextView
                android:id="@+id/data1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="Search data "
                android:textColor="#1D1D1D"
                android:textSize="16sp" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" >

            <AutoCompleteTextView
                android:id="@+id/data2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="Search data "
                android:textColor="#1D1D1D"
                android:textSize="16sp" />
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

</RelativeLayout>


Here we are using two AutoCompleteTextView as we will show auto complete in two ways. First case is when  either user  enter his/her own data or choose from dropdown list,but in case you don't want user to enter data on his own will, you can restrict him/her by disabling keyboard. We will be doing both cases.

Before we proceed, please add library "android design library" as I have used material design component in XML file. In case you don't want to add library, just remove

<android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" >


 from both AutoCompleteTextView.


Create an string array in strings.xml file which can be found in "res>values>strings.xml"

For example, I am using this array:


  <string-array name="data_array">
        <item>Android 2.2</item>
        <item>Android 4.4</item>
        <item>Android 5.0</item>
        <item>Linux Mint 16</item>
        <item>Linux Mint 17</item>
        <item>Linux Mint 18</item>
    </string-array>



After that, add below code in your MainActivity.java :

package com.example.autocompletehandling;
import android.support.v7.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
 
    private AutoCompleteTextView autoCompleteEditText1,autoCompleteEditText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF0000")));
        getSupportActionBar().setTitle("Autocomplete Handling");
     
        autoCompleteEditText1=(AutoCompleteTextView) findViewById(R.id.data1);
        autoCompleteEditText2=(AutoCompleteTextView) findViewById(R.id.data2);
        String[] dataArray1 = getResources().getStringArray(R.array.data_array);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                dataArray1);
     
        String[] dataArray2 = getResources().getStringArray(R.array.data_array);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                dataArray2);
        autoCompleteEditText1.setAdapter(adapter1);

        autoCompleteEditText2.setAdapter(adapter2);
        autoCompleteEditText1.setThreshold(1);
     
        autoCompleteEditText1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
                // TODO Auto-generated method stub
                String Data = (String) parent.getItemAtPosition(position);
                Toast.makeText(MainActivity.this, "You have clicked: "+Data+" at position:"+position, Toast.LENGTH_SHORT).show();
            }
        });


        autoCompleteEditText2.setOnItemClickListener(new OnItemClickListener()  {

            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
                // TODO Auto-generated method stub
                String Data = (String) parent.getItemAtPosition(position);
                Toast.makeText(MainActivity.this, "You have clicked: "+Data+" at position:"+position, Toast.LENGTH_SHORT).show();
            }
        });
     
    
        autoCompleteEditText2.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
                autoCompleteEditText2.showDropDown();
                autoCompleteEditText2.setKeyListener(null);
                return false;
            }
        });
     
     
    }
 
}


In the above code, as you can see first we have declared two AutocompleteTextView and then initialised them.

After that, we have used two string array dataArray1 and dataArray2 which stores values of string array that we have created in strings.xml (In my case, it is data_array).

Then, we have used ArrayAdapter "adapter1" and "adapter2" to store values of String arrays dataArray1 and dataArray2 in Adapter.

Now we will set adapter for AutoCompleteTextView autoCompleteEditText1 and autoCompleteEditText2 using:

autoCompleteEditText1.setAdapter(adapter1);

autoCompleteEditText1.setAdapter(adapter2);


autoCompleteEditText1 will serve the first case where user can either his/her own data or choose from dropDown list.


Auto suggestion as per your entry
You have selected item




For second case, we are using .setOnTouchListener() method which will show items in dropdown with autoCompleteEditText2.showDropDown() and will not allow user to enter own data as we have disabled the keyboard using autoCompleteEditText2.setKeyListener(null).
Show Dropdown and disable keypad
You have selected item



Then, we have used onItemClickListener which will give you the position and value of the item you have clicked.

This is the end of this article. Hope it clears your doubt. Please share and comment your. Thank you