Saturday, April 4, 2015

How to use MultiAutoCompleteTextView in Android

Android MultiAutoCompleteTextView
activity_main.xml

<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:padding="16dp"
    tools:context=".MainActivity"
    >
    <MultiAutoCompleteTextView
        android:id="@+id/mactv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidexamples;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

//additional imported classes
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.MultiAutoCompleteTextView;

public class MainActivity extends Activity {

    //Initialize a String Array with values
    String[] Colors = new String[]{
            "FireBrick","FloralWhite","ForestGreen",
            "GhostWhite","Gold","GoldenRod","Gray","Green"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Initialize an ArrayAdapter from a String Array
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this,android.R.layout.simple_dropdown_item_1line,Colors);

        //Get reference of XML Layout's MultiAutoCompleteTextView widget
        MultiAutoCompleteTextView macTextView = (MultiAutoCompleteTextView) findViewById(R.id.mactv);

        //Apply ArrayAdapter to MultiAutoCompleteTextView
        macTextView.setAdapter(adapter);

        //Define the AutoCompletion Threshold
        macTextView.setThreshold(1);
        //Define the AutoComplete DropDown width
        macTextView.setDropDownWidth(300);

        //Set a simple Comma Tokenizer to separate list items
        macTextView.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.menu_main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}




More android examples