如何在用户输入文本时使用光标更新列表视图

时间:2011-06-28 21:09:44

标签: android listview cursor adapter

我完全难过!我一直在寻找年龄,但找不到解决方案。我觉得它会变得非常简单!

Anway,我有一个绑定到光标的listview,每次用户输入一个字母时,我都希望listview搜索数据库并返回结果。这听起来很简单,但我无法弄清楚。在此先感谢您的帮助。

这是我到目前为止的代码:

public class MyList extends ListActivity {


    public static final String KEY_ROWID = "headwords._id";
    public static final String KEY_WORDS = "headwords.words";
    private ListAdapter adapter;
    private DbManager myDb;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.item_list);


        myDb = new DbManager(this);
        myDb.open();
        Cursor mCursor = myDb.startsWith("a");
        startManagingCursor(mCursor);



        try {
        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, mCursor, 
                new String[] { KEY_WORDS, KEY_ROWID },
                new int[] { android.R.id.text1, android.R.id.text2 });
                setListAdapter(adapter);

        } catch (Exception e) {
            Log.i("adapter error Here!", ">>>>>>>>>>> Error!" + e.toString());
        }








        EditText myET = (EditText) findViewById(R.id.search_text);
        myET.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //code which would change listview to only show item that match what is being typed in
            }

            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {    
            }

        });

    }

1 个答案:

答案 0 :(得分:0)

首先让mCursor成为会员:

private Cursor mCursor;

@Override
public void onCreate(Bundle icicle) {
  mCursor = myDb.startsWith("a");
}

然后在我的例子中,我正在接受CharSequence的第一个字母,但这可能不是你想做的,但关键是changeCursor();

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
  mCursor = myDb.startsWith(s.toString.substring(0,1));
  adapter.changeCursor(mCursor);
}