美文网首页
RecycleView添加Header

RecycleView添加Header

作者: 美晨菌 | 来源:发表于2020-09-04 21:23 被阅读0次
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);
  }

相关文章

网友评论

      本文标题:RecycleView添加Header

      本文链接:https://www.haomeiwen.com/subject/rdcgsktx.html