android - 获取视图在 GridLayoutManager 上的列号
问题描述
RecyclerView
我使用GridLayoutManager
带有动态列号的方式呈现不同类型的项目。问题是,我有一个RecyclerView.ItemDecoration
要申请的,比如说Type A
项目。这RecyclerView.ItemDecoration
将向左侧/开始添加左侧列上的那些项目的边距,并在右侧列上的那些项目的右侧/结束处添加边距。这基本上是为了使项目看起来更居中,因此被拉伸(这用于平板电脑/横向模式)。RecyclerView
网格看起来像这样:
| A | | A |
| A | | A |
| B |
| A | | A |
| A | | A |
| B |
| A | | A |
ItemDecoration
看起来像这样:
class TabletGridSpaceItemDecoration(private val space: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) = with(outRect) {
val isTypeAItemLayout = view.findViewById<ConstraintLayout>(R.id.type_a_item_container) != null
if (isTypeAItemLayout) {
val adapterPosition = parent.getChildAdapterPosition(view)
if (adapterPosition % 2 == 0) {
left = space
right = 0
} else {
left = 0
right = space
}
}
}
}
这个装饰器的问题是,在type B
列表中的第一个项目之后,下一个项目的索引被搞砸了type A
。所以根据提供的示例后的第一项B
会有adapterPosition == 5
,所以根据TabletGridSpaceItemDecoration
marging应该添加到右边,这是不正确的。
我试图
HashMap
保持adapterPosition
项目的真实位置,即忽略非type A
项目的适配器上的位置。这还有其他一些问题,我不会过多介绍细节,但感觉不是正确的方法。我尝试的另一件事是检查将要应用项目装饰的视图屏幕上的位置(更靠左或靠右)。这样做的问题是,当这个装饰器运行时,视图还没有被渲染。在视图上添加 a
ViewTreeObserver.OnGlobalLayoutListener
是没有价值的,因为在呈现视图时,已经应用了项目装饰,这对视图没有任何影响。
我想做的是检查一个项目是否在“第 0 列”或“第 1 列”中,并相应地添加边距。
我不知道这怎么可能,也没有找到方法来查看GridLayoutManager
提供的内容,可以通过parent.layoutManager as GridLayoutManager
.
有任何想法吗?谢谢
解决方案
我将其作为答案分享,因为评论太长了。让我知道结果,然后,如果不起作用,我将删除。
另外,很抱歉分享Java ..我对Kotlin不识字
而不是使用位置,您可以尝试使用spanIndex
@Override
public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent, final State state) {
...
if(isTypeAItemLayout) {
int column = ((GridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
if (column == 0) {
// First Column
} else {
// Second Column
}
}
}
更新。
对于科特林:
val column: Int = (view.layoutParams as GridLayoutManager.LayoutParams).spanIndex
推荐阅读
- docker - docker:如何在容器之间共享 ssh-keys?
- r - 文件上传从字符串匹配添加列
- jmeter - Jmeter Hbase 测试,如何进行大数据的负载测试?
- mysql - 关于 mysql 和连接池的高级问题(与 AWS 相关)
- c++ - consteval 如何影响默认参数的评估?
- nsdateformatter - 有没有办法根据我们在 swift iOS 中的要求自定义日期格式化程序
- laravel - Laravel Sanctum - 在 auth:sanctum 上获得 401,登录后返回令牌
- java - 我什至可以使用列表吗
在 Selenium 中没有 StaleElementException? - javascript - HTML画布代理getContext问题
- raspberry-pi - 将 pi Raspberry 连接到继电器