在Android中实现如同baidu\google的自动补全功能,用到AutoCompleteTextView和MultiAutoCompleteTextView组件。效果图:
?
代码:
1,res/values/string.xml
<?xml version="1.0" encoding="utf-8"?><resources> <string name="title_tx">内容自动补全提示:</string> <string name="app_name">自动提示(AutoComplete TextView)</string> <string name="about_80080088">更多详情,可登录http://www.80080088.com了解。</string></resources>
?
2,res/layout/main.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="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/title_tx" android:id="@+id/title_tx"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/about_80080088" android:id="@+id/about_80080088"> </TextView> <AutoCompleteTextView android:id="@+id/autoCompleteTextView1" android:layout_width="fill_parent" android:layout_height="wrap_content"> </AutoCompleteTextView> <MultiAutoCompleteTextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/multiAutoCompleteTextView1"> </MultiAutoCompleteTextView> </LinearLayout>
?
3.Activity类
package com.cottsoft.android;import android.app.Activity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.AutoCompleteTextView;import android.widget.MultiAutoCompleteTextView;public class A009Activity extends Activity { private static final String[] autoString = new String[]{"科特软件","cottsoft.com","80080088.com","china-loong.com","android","ophone","Windows","Lunix"}; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,autoString); AutoCompleteTextView m_AutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1); m_AutoCompleteTextView.setAdapter(adapter); MultiAutoCompleteTextView m_MultiAutoCompleteTextView = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1); m_MultiAutoCompleteTextView.setAdapter(adapter); m_MultiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); }}
?