RecyclerView自定义LayoutManager删除不需要的视图



我有一个自定义的LayoutManager(继承自LinearLayoutManager(,它需要计算每个子项的项宽度,并从RecyclerView中删除所有没有空间显示的子项。

样本代码(编辑V2(:

override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
super.onLayoutChildren(recycler, state)
// skip if orientation is vertical, for now we only horizontal custom menu
if (orientation == RecyclerView.VERTICAL) return
// skip if adapter has no items
if (itemCount == 0) return
var totalItemWidth = 0
var totalItemsCanFit = 0
// calculate menu item width and figure out how many items can fit in the screen
for (i in 0 until childCount) {
getChildAt(i)?.let { childView ->
totalItemWidth += getDecoratedMeasuredWidth(childView)
}
if (screenWidth > totalItemWidth) {
totalItemsCanFit++
}
}
// if all items can fit, do nothing and show the whole menu
if (childCount > totalItemsCanFit) {
// remove child views that have no space on screen
for (i in childCount - 1 downTo totalItemsCanFit) {
removeAndRecycleViewAt(i, recycler)
}
}
}

我有两个问题:

  • 上面的示例代码是解决这个问题的正确方法吗
  • 在看到并非所有项目都能容纳后,我如何在末尾添加一个3点图标

编辑:

为了澄清,我试图实现的是一个由RecyclerView支持的弹出菜单。菜单没有项目限制,相反,它应该计算每个项目的宽度,并删除所有没有空间的项目。此外,在末尾添加一个3点菜单项作为更多选项。

关于您的第一个问题:看看addDisappearingView(View child)是否能帮到你,根据文件:

在onLayoutChildren期间仅调用(Recycler,State(以添加查看已知正在消失的布局,原因可能是已被移除,或者因为它实际上不在可见部分容器的,但正在布局以便通知RecyclerView如何在视图之外设置项目的动画。

至于第二个问题,您只需要在您的recyclerView中实现一个"加载更多"功能。你将如何实现这取决于你的需求/设计(如果你想要一个按钮或自动滚动…(。有许多教程可供参考,例如:https://androidride.com/android-recyclerview-load-more-on-scroll-example/。

相关内容

最新更新