本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/AutoCompleteTextView和EditText很相似,事实上,AutoCompleteTextView就是EditText的子类。使用AutoCompleteTextView,当用户正在输入时,会自动弹出一些提示信息。下面的例子将会展示如何使用AutoCompleteTextView去自动地帮助用户完成输入。
1。 创建一个工程:BasicViews3。
2。 main.xml中的代码。
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Name of President" />
- <AutoCompleteTextView android:id="@+id/txtCountries"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
- public class BasicViews3Activity extends Activity {
- String[] presidents = {
- "Dwight D. Eisenhower",
- "John F. Kennedy",
- "Lyndon B. Johnson",
- "Richard Nixon",
- "Gerald Ford",
- "Jimmy Carter",
- "Ronald Reagan",
- "George H. W. Bush",
- "Bill Clinton",
- "George W. Bush",
- "Barack Obama"
- };
- /** 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, presidents);
- AutoCompleteTextView textView = (AutoCompleteTextView)
- findViewById(R.id.txtCountries);
- textView.setThreshold(3);
- textView.setAdapter(adapter);
- }
- }
