自定义 AutoCompleteTextView 从数据库中取得待选项

一、自定义 adapter,从数据库中取得待选数据,并匹配用户输入的字符

public class NameCursorAdpter extends CursorAdapter {
    private SQLiteDatabase sqlite;
    private String results;
    //引入sqlite
    public NameCursorAdpter(Context context, Cursor c, SQLiteDatabase sqlite) {
        super(context, c);
        this.sqlite = sqlite;
    }

    // 取得下拉列表中的 Item 布局,用来填入供选择的数据
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        //Log.i("info", "newView");
        final LayoutInflater inflater = LayoutInflater.from(context);
        final TextView view = (TextView) inflater.inflate(
                //android.R.layout.simple_dropdown_item_1line, parent, false);
                //android.R.layout.simple_spinner_item, parent, false);
                R.layout.name_list_item, parent, false);
        return view;
    }

    // 与上面的 newview 配合,填充供选择的下拉列表
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        //Log.i("info", "bindView");
        ((TextView) view).setText(cursor.getString(cursor.getColumnIndex("name")));
    }

    // 在下拉列表中选择某项后,显示在TextView中的值
    @Override
    public String convertToString(Cursor cursor) {
        //Log.i("info", cursor.getString(cursor.getColumnIndex("name")));
        return cursor.getString(cursor.getColumnIndex("name"));
    }

    // 根据TextView输入的字符串,在数据库中进行匹配,从而获得cursor,这个cursor包含了数据信息
    @Override
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
        if (constraint != null) {
            // 返回的列中必须包含 “_id”列
            String sql = "select * from Persons where " +
                    // 格式字符串中要使用%号,必须使用 %% 来转义
                    String.format("jm like '%%%s%%' or name like '%%%s%%' ", constraint.toString(), constraint.toString()) +
                    " order by name collate localized asc";
            Cursor Ret = sqlite.rawQuery(sql, null);
            return Ret;
        }
        else {
            return null;
        }
    }
}

二、将 adapter 绑定到 AutoCompleteTextView 上

AutoCompleteTextView edtQName = (AutoCompleteTextView) findViewById(R.id.edtQName);
nameAdpter = new NameCursorAdpter(this, null, db);
edtQName.setAdapter(nameAdpter);
// 输入一个字符后就展开列表
edtQName.setThreshold(1); 

三、布局文件,是从 android 的 simple_dropdown_item_1line.xml 复制过来的

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/spinnerItemStyle"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:ellipsize="marquee"
    android:gravity="center_vertical"
    android:singleLine="true"
    android:textAlignment="inherit" />

更复杂的用法可参考 android开发之自定义AutoCompleteTextView

posted @ 2022-01-06 20:28  汉学  阅读(99)  评论(0)    收藏  举报