Day 8: AutoComplete Text View in Android

Introduction

 
You have often encountered auto-complete text boxes in mobile applications and websites. Usually, they are made to show suggestions for what we actually want to write. In this context, you can say Visual Studio's Intellisense is feasible to auto-complete you syntax before you do.
 
Whenever you search for someone on Facebook, it shows your suggestions.
 
And Google Search itself is a great example of an autocomplete search box.
 
Google Search
 
This article shows how to create a demo-app for an auto-complete text view.
 
Procedure
Step 1
Create a successful Android project and add an Auto Complete Text View from the Palette's Text Field.
 
Code
  1. <AutoCompleteTextView  
  2.         android:id="@+id/autoCompleteTextView1"  
  3.         android:layout_width="wrap_content"  
  4.         android:layout_height="wrap_content"  
  5.         android:layout_gravity="center"  
  6.         android:ems="10"  
  7.         android:text="" >  
And, it will look like something as in the following:
 
Google Search 1
 
Here, I have added an extra TextView (“Suggest Your Mobile OS”).
Step 2
We will now code the Java part. Here, we will import the desired packages.
 
Code
  1. import android.widget.ArrayAdapter;    
  2. import android.widget.AutoCompleteTextView;    
Step 3
Now, we need a string array to populate the AutoComplete Text View. Fot this, we have used a string array that consists of the various platform names.
 
Code
  1. String[] mobileOs={"Android""Windows Phone""Apple iOS""Blackberry""JOLLA""Firefox OS""Symbian""Manroid""Ubuntu OS"};  
Step 4
After doing all this, we will create an ArrayAdapter instance and then bind this with an AutoComplete TextView instance.
 
So, let's do it.
 
Code
  1. // Create Instance of ArrayAdapter and bind it with mobilOS array.  
  2. ArrayAdapter<String> adapter =new ArrayAdapter<String>(MainActivity.this, android.R.layout.select_dialog_item, mobileOs);  
  3.           
  4. // Link the Auto Complete Text View  
  5. AutoCompleteTextView autoText =(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);  
  6. autoText.setThreshold(1); // Start From 1st Character  
  7. autoText.setAdapter(adapter);  
Explanation
 
In the ArrayAdapter's instance, we are binding with a mobile OS string array and then we linked that array adapter to an auto-complete text box.
 
After Rendering, it will look like,
 
ArrayAdapter
 

Conclusion

 
If you experience any kind of problem or red line issue then always go for the Quick Fix (Ctrl+1) since it will definitely help you.
 
If however it doesn't work then go for the solution file that I have attached.


Similar Articles