从上一个例子(Android自动补全教程 http://www.linuxidc.com/Linux/2012-01/51326.htm )可以看到自动补全是很简单的,今天再深入一点,ArrayAdapter提供的字符串从数据库中查询,并且使用MultiAutoCompleteTextView控件。此控件和AutoCompleteTextView的最大区别是可以补全多个词,看名字就能知道,呵呵。效果如下,每个词中间用逗号分割。
首先布局和上一个例子相同。创建一个名为list_item.xml的XML文件并把它保存在res/layout/文件夹下。编辑文件像下面这样:
[html] - <?xml version="1.0" encoding="utf-8"?>
- <TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- android:textSize="16sp"
- android:textColor="#000">
- </TextView>
这个文件定义了一个简单的TextView来显示提示列表的每一项。打开 res/layout/main.xml文件加入如下内容:
[html] - <?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:id="@+id/tv"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
- <MultiAutoCompleteTextView
- android:id="@+id/mactv"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
下面就来设计我的数据库,名字为person,要建一个person表,有两个字段:name和gender。 新建一个SQLiteHelper类,继承自SQLiteOpenHelper:
[java] - package com.linc.autosqlite.dao;
-
-
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
-
- /**
- * 实现对表的创建、更新、变更列名操作
- * @author lincyang
- *
- */
- public class SQLiteHelper extends SQLiteOpenHelper {
- public static final String DB_NAME = "person";
- public static final int DB_VERSION = 1;
- protected static Context ctx;
-
- //
- //构造函数一:传context
- //
- public SQLiteHelper(Context context) {
- super(context, DB_NAME, null, DB_VERSION);
- ctx = context;
- }
- //
- //构造函数二
- //
- public SQLiteHelper() {
- super(ctx,DB_NAME, null, DB_VERSION);
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
- String sql = "create table person(name varchar(20) not null , " +
- "gender varchar(10) not null );";
- db.execSQL(sql);
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // TODO Auto-generated method stub
-
- }
- protected void closeCursor(Cursor cursor) {
- if (cursor != null) {
- cursor.close();
- }
- }
- }