安卓开发学习之AutoCompleteTextView

最近在学习安卓开发,开始是看视频学的,基本上是照着老师的操作来,但其实老师也是按照安卓的开发文档来教的,于是决定试试自己看文档来学。

今天学到AutoCompleteTextView,一上来先按照ListView的操作流程:

1.获取对象

2.创建Adapter对象实现BaseAdapter接口

3.setAdapter

结果发现这不行。。因为从源码中可以看到adapter参数必须是一个filterable list adapter!

 /**
     * <p>Changes the list of data used for auto completion. The provided list
     * must be a filterable list adapter.</p>
     * 
     * <p>The caller is still responsible for managing any resources used by the adapter.
     * Notably, when the AutoCompleteTextView is closed or released, the adapter is not notified.
     * A common case is the use of {@link android.widget.CursorAdapter}, which
     * contains a {@link android.database.Cursor} that must be closed.  This can be done
     * automatically (see 
     * {@link android.app.Activity#startManagingCursor(android.database.Cursor) 
     * startManagingCursor()}),
     * or by manually closing the cursor when the AutoCompleteTextView is dismissed.</p>
     *
     * @param adapter the adapter holding the auto completion data
     *
     * @see #getAdapter()
     * @see android.widget.Filterable
     * @see android.widget.ListAdapter
     */
    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
        if (mObserver == null) {
            mObserver = new PopupDataSetObserver();
        } else if (mAdapter != null) {
            mAdapter.unregisterDataSetObserver(mObserver);
        }
        mAdapter = adapter;
        if (mAdapter != null) {
            //noinspection unchecked
            mFilter = ((Filterable) mAdapter).getFilter();
            adapter.registerDataSetObserver(mObserver);
        } else {
            mFilter = null;
        }

        mPopup.setAdapter(mAdapter);
    }

官方文档是这么写的

1.Add the AutoCompleteTextView to your layout. Here's a layout with only the text field:

<?xml version="1.0" encoding="utf-8"?>
<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/autocomplete_country"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

2.Define the array that contains all text suggestions. For example, here's an array of country names that's defined in an XML resource file (res/values/strings.xml):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="countries_array">
        <item>Afghanistan</item>
        <item>Albania</item>
        <item>Algeria</item>
        <item>American Samoa</item>
        <item>Andorra</item>
        <item>Angola</item>
        <item>Anguilla</item>
        <item>Antarctica</item>
        ...
    </string-array>
</resources>

3.In your Activity or Fragment, use the following code to specify the adapter that supplies the suggestions:

// Get a reference to the AutoCompleteTextView in the layout
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
// Get the string array
String[] countries = getResources().getStringArray(R.array.countries_array);
// Create the adapter and set it to the AutoCompleteTextView 
ArrayAdapter<String> adapter = 
        new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
textView.setAdapter(adapter);
Here, a new ArrayAdapter is initialized to bind each item in the COUNTRIES string array to a TextView that exists in the simple_list_item_1 layout (this is a layout provided by Android that provides a standard appearance for text in a list).
Then assign the adapter to the AutoCompleteTextView by calling setAdapter().

那么问题来了,这是从xml中读取的列表,如果我要自己生成列表怎么做呢?如果看源码就很清楚了

/**
     * Constructor
     *
     * @param context The current context.
     * @param resource The resource ID for a layout file containing a layout to use when
     *                 instantiating views.
     * @param textViewResourceId The id of the TextView within the layout resource to be populated
     * @param objects The objects to represent in the ListView.
     */
    public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) {
        init(context, resource, textViewResourceId, Arrays.asList(objects));
    }

这是ArrayAdapter的构造方法,所以我们还要创建一个simple_list_item_1.xml文件,在这个布局中写入一个TextView,可以设置其ID为textView1,那么此时我们就可以创建一个ArrayAdapter的实例化对象了

// text变量用来存储提示用户输入的列表
String[] text = { "a", "ab", "abc", "abcd" }; // 创建ArrayAdapter对象 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item, R.id.textView1, text);

按照上面方法即可实现带输入提示的输入框。

----------------------------------------------------------------------------------------------------------------------------------------

刚刚看到Spinner控件的时候遇到了同样的问题,才发现上面的处理方法其实是有问题的,也就是按照官方文档说的simple_list_item_1.xml其实是不需要自己创建的,这是安卓的资源文件里面自带的,但是要注意的是这个文件的目录在android.R.layout.simple_list_item_1,关键在前面的android.R,也就是说这个文件不在当前工程目录下,在安卓提供的R文件中定义了常量。

原文地址:https://www.cnblogs.com/zhuangshq/p/5673561.html