首先,在布局檔案main.xml中添加AutoCompleteTextView元件,代碼如下:
- <?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"
- >
- <AutoCompleteTextView
- android:id="@+id/auto_complete"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
然後在MainActivity.java中定義需要綁定的資料,并将其綁定到元件上。代碼如下:
- public class MainActivity extends Activity {
- // 定義一組需要綁定的資料
- private static final String[] COUNTRIES = new String[] { "China", "Russia",
- "Germany", "USA", "Chinal", "Germany1", "China12" };
- /** 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, COUNTRIES);
- AutoCompleteTextView textview = (AutoCompleteTextView) findViewById(R.id.auto_complete);
- textview.setAdapter(adapter);
- }
- }