gpt4 book ai didi

android - 如何在 RecyclerView ItemDecoration 中获取偏移量

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:40:00 26 4
gpt4 key购买 nike

我为 RecyclerView 编写了两个 ItemDecorator。每个都在 getItemOffsets() 中添加一些顶部偏移量。比方说:

  • 第一个装饰器添加 20dp 顶部偏移
  • 第二个 decrator 添加 30dp 顶部偏移

现在,当我将它们都添加到 RecyclerView 时,每个项目都正确偏移了 50dp,这很好。

但是问题来了:如何在 onDraw/onDrawOver 中获取此偏移量?

通常装饰器通过遍历 parent.getChildAt(i) 东西并获取 child.getTop() 来绘制他们的东西,例如在 RecyclerView 的 subview 上方绘制

但在这种情况下,这样做会混淆其他装饰器的绘制,因为它还会使用 child.getTop()

所以目前看来两个装饰器都需要了解彼此以及彼此的高度。

我是不是漏掉了什么?我希望我是。

编辑: 我向 Android 问题跟踪器报告了一个问题,看来这个问题会得到解决。对其加注星标以跟踪进度: https://code.google.com/p/android/issues/detail?id=195746

最佳答案

tl;dr 不,您没有遗漏任何东西。但是您可以在 getItemOffsets 中获取所需的值,尽管这对我来说似乎有点脏。

除了自己管理装饰之外,基本上只有一个选项可以获取装饰高度:LayoutManager.getDecoratedTop();

onDraw

onDraw 中,您可以获得 recyclerView 的整个 Canvas ,c.getClipBounds() 不包含任何信息。尽管添加装饰的 javadoc 说装饰应该只在 它们的 范围内绘制。

此外,获取 parent.getLayoutManager().getDecoratedTop() 将为您在每个装饰中提供相同的值,因为这里已经太晚了,这些值用于布局目的。

我们来不及了,布局已经完成,我们错过了。

getItemOffsets

Please note that I tested the following with a LinearLayoutManager and it might as well not work with the others (Most definitely not with most custom ones). Since I am relying on measuring happening between those calls, which is not documented, the given solution might break with some future version.

我只是觉得我需要免责声明。我找到了一个可行的解决方案(观看 mOffset):

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
mOffset = parent.getLayoutManager().getTopDecorationHeight(view);
outRect.set(0, 10, 0, 0);
}

这是可行的,因为 recyclerview 在计算 child 的总插图时是 updating the views package local LayoutParams variable .虽然我们无法访问布局参数变量本身,但调用 getTopDecorationHeight 实际上使用了(当前)脏插图,为我们提供了正确的值。
因此,您可以在应用自己的装饰之前获取之前装饰的偏移量!

要应用它,只需在绘制装饰时移除其他装饰偏移即可:

c.drawRect(child.getLeft() + child.getTranslationX(),
mOffset + layoutManager.getDecoratedTop(child) + child.getTranslationY(),
child.getRight() + child.getTranslationX(),
child.getBottom() + child.getTranslationY(), paint);

这实际上会应用其他装饰偏移,然后从正确顶部绘制您自己的装饰。

一些问题

这现在是默认用例 的基本可行解决方案。 但是。如果您根据项目 VIEW_TYPE 或适配器位置有不同的偏移量,事情就会变得棘手。

您将复制您的逻辑并为各种 View 类型保留各种偏移量,或者您必须为每个 View 或 View 类型存储/检索偏移量。

为此,您可以使用 view.setTag(key, object) 添加一些自定义标记,或者对正在传递的 RecyclerView.State 对象执行类似操作周围。

关于android - 如何在 RecyclerView ItemDecoration 中获取偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881945/

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