Android MultiAutocompleteTextView

Filed Under: Android

In this tutorial, we’ll be discussing and implementing the MultiAutocompleteTextView widget in our application.

Android MultiAutoCompleteTextView

MultiAutoCompleteTextView extends AutoCompleteTextView. Unlike AutoCompleteTextView which shows the suggestion for only one string, a MultiAutoCompleteTextView shows you suggestions for each of the substrings you enter separated by a token.

This feature is fairly common in places such as specifying multiple tags(Ever came across that on StackOverflow or Github?). You must have used that when sending messages to multiple people too.

An AutoCompleteTextView only offers suggestion about the whole text.

How is it implemented?

A Tokenizer instance is set on the MultiAutoCompleteTextView instance. By default in Android, we have a CommaTokenizer built-in class to separate the auto complete strings by commas. Once a string is selected from the dropdown, the comma is appended to mark the end of that substring.

The Tokenizer is set inside the method setTokenizer().

Another important method: setThreshold() is used to specify the number of characters after which the dropdown with the autocomplete suggestions list would be displayed.

Let’s jump to the coding part.

Project Structure

androidmultiautocompletetextview project

Code

The code for the activity_main.xml class is given below:


<?xml version="1.0" encoding="utf-8"?>
<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:layout_gravity="center"
    android:layout_margin="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Separated by Commas"
        android:textSize="18sp" />

    <MultiAutoCompleteTextView
        android:id="@+id/multiAutoCompleteTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:ems="10"
        android:hint="Enter here" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Separated by Custom Token"
        android:textSize="18sp" />

    <MultiAutoCompleteTextView
        android:id="@+id/multiAutoCompleteTextViewCustom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:ems="10"
        android:hint="Add tags here" />


</LinearLayout>

The first MultiAutoCompleteTextView could use a Comma Tokenizer. The second would use a custom one – Space Tokenizer.

The code for the SpaceTokenizer.java is given below:


package com.journaldev.androidmultiautocompletetextview;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.MultiAutoCompleteTextView;

public class SpaceTokenizer implements MultiAutoCompleteTextView.Tokenizer {

    public int findTokenStart(CharSequence text, int cursor) {
        int i = cursor;

        while (i > 0 && text.charAt(i - 1) != ' ') {
            i--;
        }
        while (i < cursor && text.charAt(i) == ' ') {
            i++;
        }

        return i;
    }

    public int findTokenEnd(CharSequence text, int cursor) {
        int i = cursor;
        int len = text.length();

        while (i < len) {
            if (text.charAt(i) == ' ') {
                return i;
            } else {
                i++;
            }
        }

        return len;
    }

    public CharSequence terminateToken(CharSequence text) {
        int i = text.length();

        while (i > 0 && text.charAt(i - 1) == ' ') {
            i--;
        }

        if (i > 0 && text.charAt(i - 1) == ' ') {
            return text;
        } else {
            if (text instanceof Spanned) {
                SpannableString sp = new SpannableString(text + " ");
                TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
                        Object.class, sp, 0);
                return sp;
            } else {
                return text + " ";
            }
        }
    }
}

The methods findTokenStart findTokenEnd and terminateToken are a part of the Tokenizer interface and are implemented.

The code for the MainActivity.java class is given below


package com.journaldev.androidmultiautocompletetextview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.MultiAutoCompleteTextView;

public class MainActivity extends AppCompatActivity {


    MultiAutoCompleteTextView multiAutoCompleteTextView, multiAutoCompleteTextViewCustom;

    String[] randomSuggestions = {"a", "aa", "ab", "aab", "abc", "abcd", "abcde", "abcdef"};
    String[] tags = {"Java", "JavaScript", "Spring", "Java EE", "Java 8", "Java 9", "Java 10", "SQL", "SQLite"};

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

        multiAutoCompleteTextView = findViewById(R.id.multiAutoCompleteTextView);
        multiAutoCompleteTextViewCustom = findViewById(R.id.multiAutoCompleteTextViewCustom);

        ArrayAdapter<String> randomArray = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, randomSuggestions);
        multiAutoCompleteTextView.setAdapter(randomArray);
        multiAutoCompleteTextView.setThreshold(1);

        multiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());


        ArrayAdapter<String> tagArray = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, tags);
        multiAutoCompleteTextViewCustom.setAdapter(tagArray);
        multiAutoCompleteTextViewCustom.setThreshold(2);

        multiAutoCompleteTextViewCustom.setTokenizer(new SpaceTokenizer());

    }
}

The output of the above application in action is given below:

android multi-autocompletetextview

This brings an end to this tutorial. You can download the project source code from the link below.

Comments

  1. Thomas says:

    Hello friend, how we stop the multi autocomplete textview to show words on 3 time?
    e.g.: a, aw, awa

    And can’t continue other and other words?

  2. Mustafa Shaikh says:

    How to fetch data from server…??? any tutorial in this

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages