先上图,看效果:
先简单的介绍下AutoCompleteTextView 控件的基本用法:这个在android的sdk里也是有介绍的,下面是sdk中介绍的实现代码:
public class CountriesActivity extends Activity { protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.countries); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, COUNTRIES); AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.countries_list); textView.setAdapter(adapter); } private static final String[] COUNTRIES = new String[] { "Belgium", "France", "Italy", "Germany", "Spain" }; }从上面的代码可到实现这个功能是很简单的,只要将一个要提示的数组绑定到ArrayAdapter中,再将ArrayAdapter和 AutoCompleteTextView 控件绑定一起。
下面来说下我的功能的实现方式:
public class AutoTestActivity extends Activity {
/** Called when the activity is first created. */
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addItems();
AutoCompleteTextView ac = (AutoCompleteTextView)findViewById(R.id.autocomplete);
SimpleAdapter notes = new SimpleAdapter(
this,
list,
R.layout.main_item_three_line_row,
new String[] { "brandSearchText", "brandName"},
new int[] { R.id.searchText, R.id.brandName } );
ac.setAdapter(notes);
ac.setThreshold(1);
ac.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView tv = (TextView)arg1.findViewById(R.id.brandName);
ac.setText(tv.getText().toString()+" ");
ac.setSelection((ac.getText().toString()).length());
}
});
}
private void addItems() {
HashMap<String,String> item;
item = new HashMap<String,String>();
item.put( "brandSearchText", "NOKIA nuojiya NJY");
item.put( "brandName", "诺基亚");
list.add( item );
item = new HashMap<String,String>();
item.put( "brandSearchText", "SVMSUN SX sanxing");
item.put( "brandName", "三星");
list.add( item );
item = new HashMap<String,String>();
item.put( "brandSearchText", "摩托罗拉 moto MTLL motuoluola motoloar");
item.put( "brandName", "摩托罗拉");
list.add( item );
}
}
1.我这里将不使用ArrayAdapter而是用SimpleAdapter。
<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:id="@+id/brandName" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/searchText"
android:visibility="gone" />
</LinearLayout>
ac.setOnItemClickListener(new OnItemClickListener(){
到了这里就基本完成了。@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView tv = (TextView)arg1.findViewById(R.id.brandName);
ac.setText(tv.getText().toString()+" ");
ac.setSelection((ac.getText().toString()).length());
}
});