AutoCompleteTextView 连接数据库自动提示

这个简单例子也体现MVC的思想。AutoCompleteTextView 就是View,而SimpleCursorAdapter就是Controller,SQLiteOpenHelper就相当于Model。


1、首先定义MVC中的Model,自定义DBHelper类继承SQLiteOpenHelper用于访问数据库

  1. import android.content.Context;
  2. import android.database.Cursor;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.database.sqlite.SQLiteOpenHelper;

  5. public class DBHelper extends SQLiteOpenHelper {
  6. private static final int DATABASE_VERSION = 1;
  7. private static final String DATABASE_NAME = "autoComplete.db";
  8. // 根据name自动查询
  9. public static final String NAME = "name";
  10. public DBHelper(Context context) {
  11. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  12. }
  13. @Override
  14. public void onCreate(SQLiteDatabase db) {
  15. String sqlString = "createtable test (_id integer primary key autoincrement,name varchat(20) not null onconflict fail)";
  16. db.execSQL(sqlString);
  17. // 初始数据库表
  18. String[] nameStrArrayStr = new String[] { "aaa", "abc", "cde", "中国", "美女", "提示" };
  19. for (int i = 0; i < nameStrArrayStr.length; i++) {
  20. db.execSQL("INSERT INTOtest(" + NAME + ")values(?)",new Object[] { nameStrArrayStr[i] });
  21. }
  22. }
  23. @Override
  24. public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
  25. // do nothing here
  26. }

  27. public Cursor query(String name) {
  28. SQLiteDatabase db = this.getReadableDatabase();
  29. return db.rawQuery("select* from test where name like '%" + name + "%' limit 10",null);
  30. }
  31. }
复制代码
2、定义AutoCompleteAdater继承SimpleCursorAdapter控制数据交互

  1. import android.content.Context;
  2. import android.database.Cursor;
  3. import android.widget.SimpleCursorAdapter;

  4. public class AutoCompleteAdater extends SimpleCursorAdapter {
  5. private DBHelper dbHelper = null;
  6. private Context context;
  7. // 查询字段
  8. private String queryField;
  9. public AutoCompleteAdater(Context context, int layout, Cursor c,String from, int to) {
  10. super(context, layout, c, new String[] { from },new int[] { to });
  11. this.context = context;
  12. this.queryField = from;
  13. }

  14. @Override
  15. public Cursor runQueryOnBackgroundThread(CharSequenceconstraint) {
  16. if (constraint != null) {
  17. return getDbHelper().query((String) constraint);
  18. } else {
  19. return null
  20. }
  21. }

  22. @Override
  23. public CharSequence convertToString(Cursor cursor) {
  24. return cursor.getString(cursor.getColumnIndex(queryField));
  25. }
  26. public DBHelper getDbHelper() {
  27. if (dbHelper == null) {
  28. dbHelper = new DBHelper(this.context);
  29. }
  30. return dbHelper;
  31. }
  32. }
复制代码
3、最后定义View

  1. android:id="@+id/autoCompleteTextView1"
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. android:text=""
  5. android:hint="@string/dbAutoComlete" >



复制代码
4、在Activity中关联View和Adapter


  1. public void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.main);
  4. AutoCompleteAdatercursorAdapter = new AutoCompleteAdater(this, android.R.layout.simple_dropdown_item_1line,null, DBHelper.NAME, android.R.id.text1);
  5. // 设置输入一个字符就弹出提示列表(默认输入两个字符时才弹出提示)
  6. ((AutoCompleteTextView) this.findViewById(R.id.autoCompleteTextView1)).setThreshold(1);
  7. ((AutoCompleteTextView) this.findViewById(R.id.autoCompleteTextView1)).setAdapter(cursorAdapter);
  8. }

复制代码
0_1329446967yx6A.gif
2012-9-25 11:15 上传
下载附件 (22.89 KB)


下载地址:http://download.csdn.net/detail/goleftgoright/4069418[/url]

android AutoCompleteTextView 实现输入提示,类似百度支持输入拼音提示中文

android 的 AutoCompleteTextView 控件实现了输入框的输入提示功能,这个功能更加使用于国外的手机用户来使用。而很多时候国人更多的是要象百度那样我输入的是拼音也能将中文提示出来,如: 输入xinlang  就能提示:新浪、新浪微博等。又或者是输入:xl 拼音首字母也能做到。这样的提示才是更加的符合国人的习惯。

先上图,看效果:


        先简单的介绍下AutoCompleteTextView 控件的基本用法:这个在android的sdk里也是有介绍的,下面是sdk中介绍的实现代码:

public class CountriesActivity extends Activity {
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.countries);

         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                 android.R.layout.simple_dropdown_item_1line, COUNTRIES);
         AutoCompleteTextView textView = (AutoCompleteTextView)
                 findViewById(R.id.countries_list);
         textView.setAdapter(adapter);
     }

     private static final String[] COUNTRIES = new String[] {
         "Belgium", "France", "Italy", "Germany", "Spain"
     };
 }
从上面的代码可到实现这个功能是很简单的,只要将一个要提示的数组绑定到ArrayAdapter中,再将ArrayAdapter和 AutoCompleteTextView 控件绑定一起。

下面来说下我的功能的实现方式:

public class AutoTestActivity extends Activity {
    /** Called when the activity is first created. */
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        addItems();
        AutoCompleteTextView ac = (AutoCompleteTextView)findViewById(R.id.autocomplete);
        SimpleAdapter notes = new SimpleAdapter( 
        this, 
        list,
        R.layout.main_item_three_line_row,
        new String[] { "brandSearchText", "brandName"},
        new int[] { R.id.searchText, R.id.brandName } );        
        ac.setAdapter(notes);
        ac.setThreshold(1);

ac.setOnItemClickListener(new OnItemClickListener(){



@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView tv = (TextView)arg1.findViewById(R.id.brandName);
ac.setText(tv.getText().toString()+" ");
ac.setSelection((ac.getText().toString()).length());
}

});
    }
    
    private void addItems() {
    HashMap<String,String> item;


    item = new HashMap<String,String>();
    item.put( "brandSearchText", "NOKIA nuojiya NJY");
    item.put( "brandName", "诺基亚");
    list.add( item );


    item = new HashMap<String,String>();
    item.put( "brandSearchText", "SVMSUN SX sanxing");
    item.put( "brandName", "三星");
    list.add( item );
   
   
    item = new HashMap<String,String>();
    item.put( "brandSearchText", "摩托罗拉  moto MTLL motuoluola motoloar");
    item.put( "brandName", "摩托罗拉");
    list.add( item );


    }


}

1.我这里将不使用ArrayAdapter而是用SimpleAdapter。

2.用程序把所有的搜索词语拼接成 brandSearchText字段,用空格隔开。比如:“诺基亚 NOKIA  njy nuojiya”,把它作为搜索词。
   注意这个拼接过程应该只做一次,然后保存在静态变量里面,以便提高效率。因为只要你的提示词的一多数据量大了就会使提示的速度减慢。
还有就是这里最好是把要提示的文本放在 brandName字段 如“诺基亚”,这样的话就不要在searchText字段中添加“诺基亚”不然提示会出现重复。
将准备好的方法放在 ArrayList<HashMap<String,String>>中这里的数据也可以是从数据库中添加
3.然后再将数据放到 SimpleAdapter 中与AutoCompleteTextView 绑定自定义一个提示显示的listItem布局,在布局只用的显示brandSearchText字段数据的textview隐藏:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/brandName" />

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/searchText"
android:visibility="gone" />
</LinearLayout>
4.这样就不会把不需要显示的内容显示出来。
到这里还有最后一步,如果不做的话这里点击提示词的某一行后,显示在输入框中的内容将会是这样的:{brandName=三星, brandSearchText=SVMSUN SX sanxing
所以最后我们要对item的点击事件做处理:

ac.setOnItemClickListener(new OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView tv = (TextView)arg1.findViewById(R.id.brandName);
ac.setText(tv.getText().toString()+" ");
ac.setSelection((ac.getText().toString()).length());
}

});

到了这里就基本完成了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值