自动补全提示最主要的是使用AutoCompleteTextView控件,继而从与控件关联的ArrayAdapter提供的字符串集合得到提示。
先上图
AutoCompleteTextViewActivity.java代码如下:
public class AutoCompleteTextViewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.autocomplete); setTitle("AutoCompleteTextView_Activity"); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_dropdown_item_1line, COUNTRIES);//第3个参数为提供数据的数组名 AutoCompleteTextView autotextView = (AutoCompleteTextView) findViewById(R.id.auto_complete); autotextView.setAdapter(adapter);//将adapter适配器添加到auto..对象中 autotextView.setThreshold(1);//设置输入几个字母开始关联,默认是2 } static final String[] COUNTRIES = new String[] { //设置数据源 "China" ,"Russia", "Germany","Ukraine", "Belarus", "USA" ,"China1" ,"China12", "Germany1", "Russia2", "Belarus1", "USA1" }; }
layout中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="wrap_content"> <AutoCompleteTextView android:id="@+id/auto_complete" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout>
当然,为了以后修改数据源及代码的方便,建议将数据添加到在layout下的strings.xml文件中去
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="countries_array"> <item>China</item> <item>China1</item> <item>China12</item> </string-array> </resources>
再将原先的数据源修改为如下即可
String[] COUNTRIES = getResources().getStringArray(R.array.countries_array);
时间: 2024-12-19 11:08:28