AutoCompleteTextView:如何更改布局中的2个字符串

时间:2012-05-29 23:13:27

标签: java android textview android-arrayadapter autocompletetextview

我正在为涉及数据库的Android应用制作搜索引擎。我目前的实施如下:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.result_item, R.id.txtVerbName, verbs);
AutoCompleteTextView txtSearch = (AutoCompleteTextView) findViewById(R.id.txtSearch);
txtSearch.setAdapter(adapter);

但是,您会注意到我已将“txtVerbName”(这是一个TextView)作为textview,其值随附加的数组(“verbs”)而更改。我如何才能使这项工作能够将值附加到txtVerbName,然后将另一个值附加到同一布局中的另一个textview?

1 个答案:

答案 0 :(得分:0)

使用自定义适配器来完成此任务:

public class AutoCompleteCursorAdapter extends CursorAdapter implements Filterable {

private TextView txtVerbName, txtVerbDefinition;
private Cursor mCursor;
private Context mContext;
private final LayoutInflater mInflater;

public AutoCompleteCursorAdapter(Context context, Cursor c) {
    super(context, c, true);
    mInflater = LayoutInflater.from(context);
    mContext = context;
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView txtVerbName = (TextView) view.findViewById(R.id.txtVerbName);
    TextView txtVerbDefinition = (TextView) view.findViewById(R.id.txtVerbDefinition);

    txtVerbName.setText(cursor.getString(1));
    txtVerbDefinition.setText(cursor.getString(2));
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    final View view = mInflater.inflate(R.layout.result_item, parent, false);
    return view;
}

@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
    // this is how you query for suggestions
    if (getFilterQueryProvider() != null) {
        return getFilterQueryProvider().runQuery(constraint);
    }
    if (constraint != null) {

        DBAdapter db = new DBAdapter(mContext);
        db.open();

        mCursor = db.getVerbsContaining(constraint);

        mCursor.moveToFirst();
        db.close();
    }
    return mCursor;
}

}