我必须实现一个图像列表,例如 pinterest 的图像列表(具有不对称行的网格),并且我StaggeredGridLayoutManager
在我的片段中以这种方式使用:
场景片段
scenarioAdapter = Adapter(mutableListOf()) {
with(requireActivity() as MainActivity) {
startImageActivity(it.imageLink, it.name)
}
}
scenarioAdapter.clearList()
val mLayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
mLayoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
scenario_list.layoutManager = mLayoutManager
scenario_list.adapter = scenarioAdapter
scenarioViewModel.getScenario()
由于此图像列表是分页的,因此我 onViewCreated
将其称为方法:
private fun initScrollListener() {
scenario_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager as StaggeredGridLayoutManager
layoutManager.invalidateSpanAssignments()
val lastVisibleItemPositions = intArrayOf(0,0)
layoutManager.findLastVisibleItemPositions(lastVisibleItemPositions)
if ((lastVisibleItemPositions[1] == scenarioAdapter.itemCount - 1) &&
scenarioAdapter.itemCount >= BuildConfig.PAGE_SIZE && keepScrolling && !alreadyRefreshed) {
alreadyRefreshed = true
scenarioViewModel.getScenario(scenarioAdapter.getPage())
}
}
})
}
它工作正常,它可以正确加载图像。
这是适配器
class Adapter(
private val items: MutableList<ScenarioModel>,
private val click: (ScenarioModel) -> Unit
) :
RecyclerView.Adapter<Adapter.ViewHolder>() {
fun update(list: MutableList<ScenarioModel>) {
this.items.addAll(list)
notifyDataSetChanged()
}
fun clearList() = items.clear()
fun getPage(): Int = (items.size / BuildConfig.PAGE_SIZE)
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.item_scenario_dynamic, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItem(items[position], click)
}
override fun getItemCount(): Int = items.size
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindItem(item: ScenarioModel, click: (ScenarioModel) -> Unit) {
GlideApp.with(itemView.context).load(item.imageLink).into(itemView.scenario_image)
itemView.setOnClickListener { click(item) }
}
}
}
问题是这样的:当显示片段时,我显示了 10 个项目。当我向下滚动时,它工作得很好。但是当我回去,向上滚动时,这些项目会做一个动画,就像它们被重新排序或重新加载一样,它每次都会改变。谁可以解决这个问题?
PS:问题与分页无关,我尝试只获取第一页,尺寸很大,但问题仍然存在。