一、AutoCompleteTextViewandroid
自動完成功能,在文本框中輸入字符,會出現匹配的自動提示。相似百度搜索。數組
XML代碼ide
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:text="城市:" /> <AutoCompleteTextView android:id="@+id/actv1" android:completionThreshold="3" //輸入多少個字符會出現提示 android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:hint="請輸入城市" > </AutoCompleteTextView> </LinearLayout >
Java代碼this
public class AutoCompleteTextViewDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.autocomplete_demo); //一、獲取頁面上的自動完成控件 AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.actv1); //二、建立一個數組,保存的數據,字符串數組或者List<String> String[] city = new String[] { "beijing1", "shenzhen1", "shenzhen2", "beijing2", "shanghai" }; //三、建立一個適配器對象,用來綁定數據到AutoCompleteTextView中的第一個爲當前Activity對象,第二個參數爲顯示的樣式,第三個爲數據源. ArrayAdapter<String> citydatapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, city); //四、將適配器綁定到AutoCompleteTextView中 actv.setAdapter(citydatapter); } }
二、MultiAutoCompleteTextViewspa
支持多選的自動完成,能夠實現相似郵箱收件人的多選效果。code
XML代碼xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="城市:" android:textSize="20sp" /> <MultiAutoCompleteTextView android:id="@+id/mactv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:completionThreshold="2" android:ems="10" android:hint="請輸入城市" /> </LinearLayout> </LinearLayout>
Java代碼:對象
public class AutoCompleteTextViewDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.autocomplete_demo); //一、獲取頁面上的自動完成控件 MultiAutoCompleteTextView mactv = (MultiAutoCompleteTextView) findViewById(R.id.mactv1); //二、建立一個數組,保存的數據,字符串數組或者List<String> String[] city = new String[] { "beijing1", "shenzhen1", "shenzhen2", "beijing2", "shanghai" }; //三、建立一個適配器對象,用來綁定數據到AutoCompleteTextView中的第一個爲當前Activity對象,第二個參數爲顯示的樣式,第三個爲數據源. ArrayAdapter<String> citydatapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, city); //四、將適配器綁定到AutoCompleteTextView中 mactv.setAdapter(citydatapter); //五、設置分隔符,以,進行分割 mactv.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); } }