Prevent re-use of some views in ListView (custom cursor-adapter)

a 夏天 提交于 2019-12-03 21:55:53
Sreejith Krishnan R

If you want to prevent the reuse of view at a certain position the do the following

@Override
public int getItemViewType(int position) {
    mCursor.moveToPosition(position);
    if (mCursor.getLong(mCursor.getColumnIndex(TodoTable.COLUMN_ID)) == ts.getRunning()){
        return IGNORE_ITEM_VIEW_TYPE;
    }
    return super.getItemViewType(position);
}

If you return IGNORE_ITEM_VIEW_TYPE in getItemViewType(position) then the view at that position will not be recycled. More info about IGNORE_ITEM_VIEW_TYPE is here

Override the getView method. If you look at the source code of CursorAdapter (link), you'll see a place where they check if the view is null. You just need to copy the whole method, and add an additional if check for ts.getRunning() == id

Here is how it should now look like -

public View getView(int position, View convertView, ViewGroup parent) {
    if (!mDataValid) {
        throw new IllegalStateException("this should only be called when the cursor is valid");
    }
    if (!mCursor.moveToPosition(position)) {
        throw new IllegalStateException("couldn't move cursor to position " + position);
    }
    View v;
    if (convertView == null || ts.getRunning() == id) {
        v = newView(mContext, mCursor, parent);
    } else {
        v = convertView;
    }
    bindView(v, mContext, mCursor);
    return v;
}

Thankfully, it looks like all the fields used in that method are protected, so you should not run into any problems.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!