1. 重写Cursor
根据是否是第一个数据判断是不是header
final class SearchContactsCursor extends MergeCursor implements SearchCursor {
private final ContactFilterCursor contactFilterCursor;
private final Context context;
static SearchContactsCursor newInstance(
Context context, ContactFilterCursor contactFilterCursor) {
MatrixCursor headerCursor = new MatrixCursor(HEADER_PROJECTION);
headerCursor.addRow(new String[] {context.getString(R.string.all_contacts)});
return new SearchContactsCursor(new Cursor[] {headerCursor, contactFilterCursor}, context);
}
private SearchContactsCursor(Cursor[] cursors, Context context) {
super(cursors);
this.contactFilterCursor = (ContactFilterCursor) cursors[1];
this.context = context;
}
@Override
public boolean isHeader() {
return isFirst();
}
@Override
public boolean updateQuery(@Nullable String query) {
contactFilterCursor.filter(query, context);
return true;
}
@Override
public long getDirectoryId() {
return Directory.DEFAULT;
}
@Override
public int getCount() {
// If we don't have any contents, we don't want to show the header
int count = contactFilterCursor.getCount();
return count == 0 ? 0 : count + 1;
}
}
2. 在CursorLoader的loadInBackground()方法中把Cursor替换成想要的Cursor
@Override
public Cursor loadInBackground() {
if (!PermissionsUtil.hasContactsReadPermissions(getContext())) {
LogUtil.i("SearchContactsCursorLoader.loadInBackground", "Contacts permission denied.");
return null;
}
return isRegularSearch ? regularSearchLoadInBackground() : dialpadSearchLoadInBackground();
}
3. 使用MatrixCursor在Cursor中添加一行数据
static SearchContactsCursor newInstance(
Context context, ContactFilterCursor contactFilterCursor) {
MatrixCursor headerCursor = new MatrixCursor(HEADER_PROJECTION);
headerCursor.addRow(new String[] {context.getString(R.string.all_contacts)});
return new SearchContactsCursor(new Cursor[] {headerCursor, contactFilterCursor}, context);
}
网友评论