gpt4 book ai didi

android - 获取 View 在 GridLayoutManager 上的列号

转载 作者:行者123 更新时间:2023-11-29 23:03:24 29 4
gpt4 key购买 nike

我使用具有动态列号的 GridLayoutManagerRecyclerView 中呈现不同类型的项目。问题是,我有一个 RecyclerView.ItemDecoration,它仅适用于 Type A 项目。此 RecyclerView.ItemDecoration 将边距添加到左侧列中那些项目的左侧/开始,并将边距添加到右侧列中那些项目的右侧/末尾。它基本上是为了让项目看起来更居中,所以拉伸(stretch)(这用于平板电脑/横向模式)。 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 项目。这还有一些其他问题,我不会详细介绍,但感觉这不是正确的方法。

  • 我尝试的另一件事是检查将应用项目装饰的 View 在屏幕上的位置(更靠左或更靠右)。这样做的问题是当这个装饰器运行时 View 还没有被渲染。在 View 上添加 ViewTreeObserver.OnGlobalLayoutListener 是没有值(value)的,因为在呈现 View 时,项目装饰已经应用,这对 View 没有影响。

我想做的是检查一个项目是否在“第 0 列”或“第 1 列”中,并相应地添加边距。

我不知道这怎么可能,也没有找到方法查看 GridLayoutManager 提供的内容,可以通过 parent.layoutManager 作为 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
}
}
}

更新。

对于 Kotlin :

val column: Int = (view.layoutParams as GridLayoutManager.LayoutParams).spanIndex

关于android - 获取 View 在 GridLayoutManager 上的列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56775671/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com