Filter rows from Cursor so they don't show up in ListView

Ric*_*ard 11 android

我有一个Cursor,它返回我使用SimpleCursorAdapter的行来填充ListView.我想过滤一些行,这样它们就不会显示在我的ListView中.我使用Activity中其他行的数据,因此我不想更改我的SQL以使用WHERE子句过滤它们.

保持一行不在ListView中显示的最佳方法是什么?理想情况下,我会检查我的行中的列,然后只向ListView添加满足条件的行.

Com*_*are 18

创建一个CursorWrapper并覆盖move...()方法,以转换过滤集中的位置(这将是ListView将要看到的)和实际位置Cursor.然后,使用你CursorWrapperSimpleCursorAdapter.


Rom*_*hev 15

谢谢,这对我有很大的帮助!如果您需要,请使用它:

private class FilterCursorWrapper extends CursorWrapper {     
    private String filter;
    private int column;
    private int[] index;
    private int count=0;
    private int pos=0;

    public FilterCursorWrapper(Cursor cursor,String filter,int column) {
        super(cursor);
        this.filter = filter.toLowerCase();
        this.column = column;
        if (this.filter != "") {
            this.count = super.getCount();
            this.index = new int[this.count];
            for (int i=0;i<this.count;i++) {
                super.moveToPosition(i);
                if (this.getString(this.column).toLowerCase().contains(this.filter))
                    this.index[this.pos++] = i;
            }
            this.count = this.pos;
            this.pos = 0;
            super.moveToFirst();
        } else {
            this.count = super.getCount();
            this.index = new int[this.count];
            for (int i=0;i<this.count;i++) {
                this.index[i] = i;
            }
        }
    }

    @Override
    public boolean move(int offset) {
        return this.moveToPosition(this.pos+offset);
    }

    @Override
    public boolean moveToNext() {
        return this.moveToPosition(this.pos+1);
    }

    @Override
    public boolean moveToPrevious() {
        return this.moveToPosition(this.pos-1);
    }

    @Override
    public boolean moveToFirst() {
        return this.moveToPosition(0);
    }

    @Override
    public boolean moveToLast() {
        return this.moveToPosition(this.count-1);
    }

    @Override
    public boolean moveToPosition(int position) {
        if (position >= this.count || position < 0)
            return false;
        this.pos = position;
        return super.moveToPosition(this.index[position]);
    }

    @Override
    public int getCount() {
        return this.count;
    }

    @Override
    public int getPosition() {
        return this.pos;
    }

}
Run Code Online (Sandbox Code Playgroud)

https://gist.github.com/ramzes642/5400792