日期:2014-05-16 浏览次数:20427 次
?AutoCompleteTextView可以根据输入的文字来显示提示, 它的Adapter可以是一个list, 也可以动态的提取数据库数据.
??写了一个例子来展示, 建立一个数据库来储存人名, 只要在AutoCompleteTextView里面输入2个字母就会显示匹配下拉单.
??这是一个定制的CursorAdapter, newView会返回一个包含cursor里文字的view, bindView把cursor的数据绑定在view里, convertToString会把view的数据转换为AutoCompleteTextView显示的文字, runQueryOnBackgroundThread方法会查询数据库.????private class MyCursorAdpter extends CursorAdapter {
????????private int columnIndex;
????????
????????public MyCursorAdpter(Context context, Cursor c, int col) {
????????????super(context, c);
????????????this.columnIndex = col;
????????}
????????@Override
????????public View newView(Context context, Cursor cursor, ViewGroup parent) {
????????????final LayoutInflater inflater = LayoutInflater.from(context);
????????????final TextView view = (TextView) inflater.inflate(
????????????????????android.R.layout.simple_dropdown_item_1line, parent, false);
????????????view.setText(cursor.getString(columnIndex));
????????????return view;
????????}
????????@Override
????????public void bindView(View view, Context context, Cursor cursor) {
????????????((TextView) view).setText(cursor.getString(columnIndex));
????????}
????????
????????@Override
????????public String convertToString(Cursor cursor) {
????????????return cursor.getString(columnIndex);
????????}
????????@Override
????????public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
????????????if (constraint != null) {
????????????????String selection = "name like \'" + constraint.toString() +"%\'";
????????????????return sqlite.query("test", columns, selection, null, null, null, null);
????????????}
????????????else {
????????????????return null;
????????????}
????????}
????}
复制代码建立数据库, 以及添加数据, 使用CursorAdapter的数据库必须包含_id项.???? private void createDatas() {
????????String createTable = "create table test (name varchar(255), _id varchar(255))";
????????sqlite.execSQL(createTable);
????????
????????ContentValues values = new ContentValues();
????????values.put("name", "nicole");
????????values.put("_id", "0");
????????sqlite.insert("test", null, values);
????????
????????values.put("name", "nicolas");
????????values.put("_id", "1");
????????sqlite.insert("test", null, values);
????????
????????values.put("name", "jean");
????????values.put("_id", "2");
????????sqlite.insert("test", null, values);
????????
????????values.put("name", "jennyfer");
????????values.put("_id", "3");
????????sqlite.insert("test", null, values);
????}
?
分享自:http://blog.csdn.net/dearbaba2011/article/details/6927444