您的位置:首页 > 移动开发 > Android开发

[Android] AutoCompleteTextView:自动完成输入内容的控件

2013-02-21 20:53 579 查看
AutoCompleteTextView是EditText的直接子类,与普通EditText的最大不同就是,在用户输入的过程中,可以列出可供选择的输入项,方便使用者。

AutoCompleteTextView与普通EditText控件使用方法类似,只是需要为其指定一个Adapter对象,绑定可供选择的输入项。

AutoCompleteTextView可实现一次自动完成的功能,而另一个控件MultiAutoCompleteTextView,可以连续多次自动完成,即在通过自动完成一个输入项,接着输入一个分隔符后,继续通过自动完成连续输入多个输入项。只是要使用MultiAutoCompleteTextView类的setTokenizer方法指定分割符。

两种自动完成输入内容的控件实例如下。

Main.java

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);     // 绑定adapter

// MultiAutoCompleteTextView
MultiAutoCompleteTextView multiAutoCompleteTextView =
(MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView);
multiAutoCompleteTextView.setAdapter(adapter);
multiAutoCompleteTextView
.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
}
}


main.xml

<?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>


程序运行效果如下图





rr 的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐