0

我想在我的 Android ListView 中添加简单的搜索过滤器,就像这里一样:

Search.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                int arg3) {

            MainActivity.this.adapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {

        }
    });

此代码来自互联网上的教程(我丢失了一个网址)。它基于 ArrayAdapter 但在我的课堂上我使用的是 SimpleCursorAdapter 并且此代码不起作用。我的意思是我可以输入,但它不会过滤搜索结果。这是我的代码:

// Create the pointer to the desired data
        dataAdapter = new SimpleCursorAdapter(
                this, R.layout.contact_row, contactsCursor, columns, to, 0);
        ListView listView = (ListView) findViewById(R.id.list);
        Search = (EditText) findViewById(R.id.inputSearch); 

        Search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                    int arg3) {

                ContactListActivity.this.dataAdapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {

            }
        });

有没有办法在 SimpleCursorAdapter 上设置这个过滤器功能?

4

1 回答 1

4
Search.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                int arg3) {
            String where = *YOURCOLUMN* + " LIKE '%" + cs + "%'";

            Cursor c = db.query(*TABLE*, *COLUMNS*, where, null, null, null, null);

            dataAdapter.swapCursor(c);
            dataAdapter.notifyDataSetChanged();
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {

        }
});

显然你需要输入你自己的数据,但在大多数情况下应该做你想做的事。希望能成功!

于 2013-07-26T15:37:37.450 回答