Android 应用开发札记 - 自动提示(AutoComplete-TextView) & ArrayAdapter

Android 应用开发笔记 - 自动提示(AutoComplete-TextView) & ArrayAdapter

4.2.4 下拉列表(Spinner)已经使用了ArrayAdapter,现在介绍下它。

 

一个具体的BaseAdapter的背后是任意对象的数组。默认情况下,这个类预期提供的资源所引用的一个单一的TextView。如果你想使用更复杂的布局,使用的构造函数还需要一个字段id。该字段id引用一个TextView在较大的布局资源。

 

然而在TextView被引用时,它会被充满的toString()数组中的每个对象。您可以添加自定义对象的列表或数组。你的对象重写toString()方法,以确定哪些文字会显示在列表中的项目。

 

下面我们开始使用这个控件。

首先,建立一个Layout XML,清单如下:

res/view_arrayadapter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:popupBackground="@color/black" />

    <MultiAutoCompleteTextView
        android:id="@+id/multiAutoCompleteTextView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:popupBackground="@color/black" />

</LinearLayout>


注意,上面有行是为弹出提示框的背景色。

android:popupBackground="@color/black"

 

 

其主要代码如下:

AutoCompleteTextView aCompTextView = 
						(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
				
				MultiAutoCompleteTextView mCompTextView = 
						(MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1);
				
				ArrayAdapter<String> arrayAdapter = 
						new ArrayAdapter<String>(
								MainActivity.this, 
								android.R.layout.simple_dropdown_item_1line,
								new String[] {
									"ab",
									"abc",
									"abcd",
									"abcde",
									"abcdef",
									"edcba",
									"dcba",
									"cba",
									"ba",
									"bcd"
								});
				
				aCompTextView.setAdapter(arrayAdapter);
				mCompTextView.setAdapter(arrayAdapter);
				mCompTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());


运行效果:

Android 应用开发札记 - 自动提示(AutoComplete-TextView) & ArrayAdapter