Tuesday, 9 July 2013

Andoird Development Example: AutoCompleteTextView and MultiAutoCompleteTextView



Dynamic auto complete for input text can be archived by AutoCompleteTextView. Here's an example to illustrate the usage of AutoCompleteTextView.

(1) layout.xml
< AutoCompleteTextView  
        Android: ID = "@ + ID / Auto"  
        Android: layout_width = "wrap_content"  
        Android: layout_height = "wrap_content"  
        Android: layout_alignParentLeft = "true"  
        Android: layout_alignParentRight = "true"  
        Android: layout_below = "@ + id/textView1"  
        Android: layout_marginTop = "20DP"  
        Android: EMS = "10"  >  
  
        < requestFocus  />  
    </ AutoCompleteTextView > 

< MultiAutoCompleteTextView  
        Android: ID = "@ + ID / multiAuto"  
        Android: layout_width = "wrap_content"  
        Android: layout_height = "wrap_content"  
        Android: layout_alignParentLeft = "true"  
        Android: layout_alignRight = "@ + ID / Auto"  
        Android: layout_below = "@ + id/textView2"  
        Android: layout_marginTop = "19dp"  
        Android: EMS = "10"  />  


(2) Main activity
package com.example.autocomplete;  
  
import android.app.Activity;  
import android.os.Bundle;  
import android.view.Menu;  
import android.widget.ArrayAdapter;  
import android.widget.AutoCompleteTextView;  
import android.widget.MultiAutoCompleteTextView;  
  
public class MainActivity extends Activity {  
    private AutoCompleteTextView auto;  
    private MultiAutoCompleteTextView mulAuto;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        auto=(AutoCompleteTextView) findViewById(R.id.auto);  
        mulAuto= (MultiAutoCompleteTextView) findViewById(R.id.multiAuto);  
        String[] autoStrings = new String[] { "Google Map", "Google", "Google Drive","Google Doc",  
                "java", "javaweb","javascript" };  
        
        ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,  
                android.R.layout.simple_dropdown_item_1line, autoStrings);  
        auto.setAdapter(adapter);  
        mulAuto.setAdapter(adapter);  
       
        mulAuto.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());  
    }  
  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.main, menu);  
        return true;  
    }  
  
}  

0 comments:

Post a Comment