實做方式就是先建立一個String 陣列,將使用者有可能輸入值都先預設好在這個陣列裡頭
透過ArrayAdapter將剛宣告的String陣列放入裡頭,在這邊比較不一樣的是,我們可以自己設計下拉式選單的頁面
Style.xml:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FF5500" android:padding="5dp" android:textColor="#00FF00" android:textSize="20sp" > </TextView>
Strings.xml:
<resources> <string name="app_name">AutoComplete</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_auto_complete">AutoComplete</string> <string-array name="list"> <item >Apple</item> <item >Air</item> <item >Ant</item> </string-array> </resources>
Code:
package com.cyfang.autocomplete; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; public class AutoComplete extends Activity { private AutoCompleteTextView autoComplete = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auto_complete); autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1); String[] str = getResources().getStringArray(R.array.list); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.style, str); autoComplete.setAdapter(arrayAdapter); } }
那不太會在xml檔案裡面建立String-array的人,可以將String宣告成一個陣列,在那個陣列裡面塞值,不過相對在記憶體空間使用率就佔比較多資源
package com.cyfang.autocomplete; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; public class AutoComplete extends Activity { private AutoCompleteTextView autoComplete = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auto_complete); autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1); String[] str = new String[] { "Apple", "Air", "Ant", "Again" }; ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.style, str); autoComplete.setAdapter(arrayAdapter); } }