自动完成输入内容的控件

可以使用AutoCompleteTextView或者MultiAutoCompleteTextView 控件来完成输入的功能。使用MultiAutoCompleteTextView控件来完成连续输入的功能,也就是说,当输入完一个字符串后,在该字符串后面输入一个逗号(,),在逗号前后可以有任意多个空格,然后再输入一个字符串,仍然会显示辅助输入的列表,但要使用MultiAutoCompleteTextView类的setTokenizer方法指定MultiAutoCompleteTextView.CommaTokenizer类的对象实例(该对象表示输入多个字符串时的分隔符为逗号)。

代码如下

package mobile.android.ch05.autotext;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;

public class Main extends Activity
{    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String[] autoString = new String[]
        { "联合国", "联合国安理会", "联合国五个常任理事国", "bb", "bcd", "bcdf", "Google", "Google Map", "Google Android" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, autoString);
        // AutoCompleteTextView
        AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
        autoCompleteTextView.setAdapter(adapter);
        // MultiAutoCompleteTextView
        MultiAutoCompleteTextView multiAutoCompleteTextView = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView);
        multiAutoCompleteTextView.setAdapter(adapter);
        multiAutoCompleteTextView
                .setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
    }
    
}

布局文件如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="AutoCompleteTextView" />
    <AutoCompleteTextView android:id="@+id/autoCompleteTextView"
        android:layout_width="fill_parent" android:layout_height="wrap_content" />
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="MultiAutoCompleteTextView" />
    <MultiAutoCompleteTextView android:id="@+id/multiAutoCompleteTextView"
        android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>

 

posted @ 2014-03-31 20:12  我是不可不戒  阅读(393)  评论(0编辑  收藏  举报