您可以在此处使用装饰器模式。
为此,Android 有CursorWrapper,这是一个...
将所有调用委托给实际游标对象的 Cursor 包装类。此类的主要用途是扩展游标,同时仅覆盖其方法的子集。
假设您的新列被称为newColumn
,并且它是类型,String
那么您可以按照以下方式做一些事情:
class MyCursorWrapper extends CursorWrapper {
private final String NEW_COLUMN = "newColumn";
@Override
public int getColumnCount() {
// Count the virtual column in
return getWrappedCursor().getColumnCount() + 1;
}
@Override
public int getColumnIndex(String columnName) {
// Return the virtual column if they are asking for it,
// otherwise just use the original
if (columnName != null && columnName.equals("newColumn") {
return getWrappedCursor().getColumnCount();
}
return mCursor.getColumnIndex(columnName);
}
public int getColumnIndexOrThrow(String columnName)
throws IllegalArgumentException {
// Same logic as getColumnIndex()
if (columnName != null && columnName.equals(NEW_COLUMN) {
return getWrappedCursor().getColumnCount();
}
return getWrappedCursor.getColumnIndexOrThrow(columnName);
}
@Override
public String getColumnName(int columnIndex) {
if (columnIndex == getWrappedCursor.getColumnCount()) {
return NEW_COLUMN;
}
return getWrappedCursor().getColumnName(columnIndex);
}
@Override
public String[] getColumnNames() {
// Add our virtual column to the result from the original Cursor
String original = getWrappedCursor().getColumnNames()
String result = new String[original.length + 1];
System.arrayCopy(original, 0, result, 0, original.length);
result[original.length] = NEW_COLUMN;
return result;
}
@Override
public String getString(int columnIndex) {
// For the last column, return whatever you need to return here
// For real columns, just delegate to the original Cursor
if (columnIndex == getWrappedCursor().getColumnCount()) {
return yourResultHere();
}
return getWrappedCursor().getString(columnIndex);
}
}