Pra*_*uah 6 android kotlin android-recyclerview android-paging-3
在新的 Paging3 库的帮助下,它使我们可以轻松地在 recyclerview 中插入项目/分隔符,如 google android codelabs 教程https://developer.android.com/codelabs/android-paging#11所示,但是如何获取在 recyclerview 中每 n 个位置插入项目的逻辑是在每个位置 10 处插入项目。
示例代码
fun searchRepo(queryString: String): Flow<PagingData<UiModel>> {
val lastResult = currentSearchResult
if (queryString == currentQueryValue && lastResult != null) {
return lastResult
}
currentQueryValue = queryString
val newResult: Flow<PagingData<UiModel>> = repository.getSearchResultStream(queryString)
.map { pagingData -> pagingData.map { UiModel.RepoItem(it) } }
.map {
it.insertSeparators<UiModel.RepoItem, UiModel> { before, after ->
if (after == null) {
// we're at the end of the list
return@insertSeparators null
}
if (before == null) {
// we're at the beginning of the list
return@insertSeparators UiModel.SeparatorItem("${after.roundedStarCount}0.000+ stars")
}
// check between 2 items
if (before.roundedStarCount > after.roundedStarCount) {
if (after.roundedStarCount >= 1) {
UiModel.SeparatorItem("${after.roundedStarCount}0.000+ stars")
} else {
UiModel.SeparatorItem("< 10.000+ stars")
}
} else {
// no separator
null
}
}
}
.cachedIn(viewModelScope)
currentSearchResult = newResult
return newResult
Run Code Online (Sandbox Code Playgroud)
如何找到上面示例代码中每10个位置添加一个item的逻辑
fun itemInsert(position: Int): Int {
return if (position % 10 == 0) //each 10 position is separator
SEPARATOR else COMMON
}
Run Code Online (Sandbox Code Playgroud)
我们遇到了同样的问题,因此决定手动计算索引。我们val index: Int在 RepoItem 构造函数中添加: 其余的是:
val newResult: Flow<PagingData<UiModel>> = repository.getSearchResultStream(queryString)
.map { pagingData ->
var index = 0
pagingData.map { UiModel.RepoItem(it, index++) }
}
.map {
it.insertSeparators<UiModel.RepoItem, UiModel> { before, after ->
if (before.index % 10) {
Do something
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然如果您仅附加数据,这可能会起作用,但如果您设置 ,则它很可能不起作用MAX_CACHE_SIZE。
| 归档时间: |
|
| 查看次数: |
1339 次 |
| 最近记录: |