版权声明:本文为博主原创文章,未经博主允许不得转载。
使用方式和listView类似,有两种方式。
第一种:使用字符串数组为内容来源:
1.在Activity布局文件activity_main.xml中创建一个 AutoCompleteTextView 控件
android:completionThreshold
=
"1" 指定了几个字母开始自动补全,这里设置成个字母就补全。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
tools:context
=
".MainActivity"
>
<
AutoCompleteTextView
android:completionThreshold
=
"1"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:id
=
"@+id/act_city"
/>
</
RelativeLayout
>
|
2.创建一个适配器的布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
android:orientation
=
"vertical"
>
<
TextView
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:id
=
"@+id/item_city"
/>
</
LinearLayout
>
|
使用步骤:
1.找控件AutoCompleteTextView act_city = (AutoCompleteTextView) findViewById(R.id.act_city);
2.创建一个Adpater
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.item_auto_city, R.id.item_city, citys);
3.设置adaper
act_city.setAdapter(arrayAdapter)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
class
MainActivity
extends
Activity {
// 创建数组
String [] citys =
new
String[] {
"河北"
,
"河南"
,
"山东"
,
"shanxi"
,
"hunan"
,
"hubei"
};
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoCompleteTextView act_city = (AutoCompleteTextView) findViewById(R.id.act_city);
//创建一个Adpater
ArrayAdapter<String> arrayAdapter =
new
ArrayAdapter<String>(
this
, R.layout.item_auto_city, R.id.item_city, citys);
//设置adaper
act_city.setAdapter(arrayAdapter);
}
}
|
第二种方法:使用XML为数据来源
下面是xml文件,在values/strings.xml中
<string-array name="str">
<item>ShanDong</item>
<item>ShanXi</item>
<item>HeNan</item>
</string-array>
下面设置ArrayAdapter
ArrayAdapter adapter=ArrayAdapter.createFromResource(this, R.array.str, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
tv.setAdapter(adapter);