在android输入自动完成功能由EditText的子类 AutoCompleteTextView
实现。如下:
1,在xml中使用
1 <AutoCompleteTextView 2 android:id="@+id/edt_autocomplete" 3 android:hint="auto complete" 4 android:layout_width="match_parent" 5 android:layout_height="wrap_content" />
2,给AutoCompleteTextView准备个 ArrayAdapter。ArrayAdapter中就是自动完成的数据。
1 // Get a reference to the AutoCompleteTextView in the layout 2 AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.auto_complete); 3 // Get the string array 4 String[] countries = getResources().getStringArray(R.array.countries_array); 5 // Create the adapter and set it to the AutoCompleteTextView 6 ArrayAdapter<String> adapter = 7 new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries); 8 textView.setAdapter(adapter);
其中数组元素是从xml中取得的,如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 <string-array name="countries_array"> 4 <item>Afghanistan</item> 5 <item>Albania</item> 6 <item>Algeria</item> 7 <item>American Samoa</item> 8 <item>Andorra</item> 9 <item>Angola</item> 10 <item>Anguilla</item> 11 <item>Antarctica</item> 12 ... 13 </string-array> 14 </resources>
它是用一个下拉的列表显示自动完成的数据,上述代码是用android.R.layout.simple_list_item_1,可以自定义这个ArrayAdapter来完成复杂的显示.