Android:如何使用simpleCursorAdapter过滤listView

时间:2013-01-04 13:12:23

标签: android listview simplecursoradapter

首先抱歉我的英文

我已经阅读了很多关于此问题的答案,但我不知道如何运行代码。

我想使用上面的EditText文本过滤我的listView。

这是我的代码:

    private DbAdapter mDbHelper;
    private EditText mSearch;




    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baes_bat_list);
        setTitle(R.string.baes_list_title);
        mDbHelper = new DbAdapter(this);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());
        mSearch = (EditText) findViewById(R.id.searchbox);

    }

    private void fillData() {

        String search = "";
        search = mSearch.getText().toString();

        // Get all of the rows from the database and create the item list
        Cursor baesCursor = mDbHelper.fetchAllBaes(search);
        startManagingCursor(baesCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{DbAdapter.BAES_NOM, DbAdapter.BAES_BAT};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.text1, R.id.text2};

        // Now create a simple cursor adapter and set it to display
     // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter baes = 
            new SimpleCursorAdapter(this, R.layout.baes_row, baesCursor, from, to);
        setListAdapter(baes);

        };

这是我的Db适配器

public Cursor fetchAllBaes(String string) {
        String [] columns=new String[]{BAES_ID +" as _id",BAES_NOM,BAES_BAT,BAES_LOC,BAES_MISESERVICE,BAES_COUP,BAES_DATE_VISITE,BAES_ETAT, BAES_SYNC};
        String [] search = null;
        return mDb.query(TABLE_BAES, columns, BAES_BAT + "= ?", search, null, null, null);
    }

我想我错过了一步,但我不知道哪一步。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我有一个工作代码,你可以试试它是否有效,

listView = (ListView) findViewById(R.id.sendToList);
        editText = (EditText) findViewById(R.id.searchList);
        adapter = new CustomListViewAdapter(this,
                R.layout.list_row, rowItems);
        listView.setAdapter(adapter);
        listView.setTextFilterEnabled(true);

        editText.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {

            }

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

            }

            public void afterTextChanged(Editable arg0) {
                sendToList.this.adapter.getFilter().filter(arg0);

            }
        });