AutoCompleteTextView从数组里面读取数据很简单,只需使用默认适配器即可,下面我们简单介绍如何将数据库与AutoCompleteTextView关联起来。
1、自定义适配器
public class MyCursorAdapter extends CursorAdapter {
private LayoutInflater layoutInflater;
public MyCursorAdapter(Context context, Cursor c,boolean autoRequery) {
super(context, c, autoRequery);
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void setView(View view, Cursor cursor)
{
TextView tvWordItem = (TextView) view;
tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id")));
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
setView(view, cursor);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
final LayoutInflater inflater = LayoutInflater.from(context);
final TextView view = (TextView) inflater.inflate(
android.R.layout.simple_dropdown_item_1line, parent, false);
setView(view, cursor);
return view;
}
@Override
public CharSequence convertToString(Cursor cursor) {
// TODO Auto-generated method stub
return cursor == null?"":cursor.getString(cursor.getColumnIndex("_id"));
}
}
2、调用方式
AutoCompleteTextView actv_lighttype = (AutoCompleteTextView) findViewById(R.id.actv_lighttype);
actv_lighttype.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String sqlStr="select 某列 as _id from 表名 where 某列 like '"+s.toString()+"%'";
Cursor cursor=dbhelper.getAllRecordsBySql(sqlStr);
MyCursorAdapter bltcadapter = new MyCursorAdapter(XXXX.this,cursor,true);
actv_lighttype.setAdapter(bltcadapter);
}
});
通过以上重写的适配器,我们可以稍微了解了SimpleCursorAdapter为什么非要有_id字段了吧,及其参数为什么要那样设置了吧。又或者我们可以编写自己的SimpleCursorAdapter了!