getAdapterPosition() 已弃用

getAdapterPosition() is deprecated

我已将我的 targetSdkVersion 从 28 更新到 30,我注意到 getAdapterPosition() 已弃用(我不确定这是何时发生的)。

documentation 中,他们这样说:

This method is deprecated.
This method is confusing when adapters nest other adapters. If you are calling this in the context of an Adapter, you probably want to call getBindingAdapterPosition() or if you want the position as RecyclerView sees it, you should call getAbsoluteAdapterPosition().

文档还说了以下内容:

Note that if you are querying the position as RecyclerView sees, you should use getAbsoluteAdapterPosition() (e.g. you want to use it to save scroll state). If you are querying the position to access the RecyclerView.Adapter contents, you should use getBindingAdapterPosition().

我的理解是:

换句话说,如果我的 Adapter 中有 4 个项目,我删除位置 0 并在项目之前查询 getAbsoluteAdapterPositiongetBindingAdapterPosition已经从ViewHolder中移除,那么getAbsoluteAdapterPosition将return0(因为view还在ViewHolder)和getBindingAdapterPositionreturn -1(因为它不再存在于适配器中)。


我通过记录以下内容测试了差异:

Log.e("difference", "getAdapterPosition = "+myHolder.getAdapterPosition()+" getBindingAdapterPosition = "+myHolder.getBindingAdapterPosition()+" getAbsoluteAdapterPosition = "+myHolder.getAbsoluteAdapterPosition());

它们return 的值完全相同。我看不出有什么不同。

我也看不出在调用 notifyItemChangednotifyDataSetChangednotifyItemRangeChanged 之前或之后有什么区别。但是当我删除位置 0 并调用 notifyItemRemoved 它 returns -1 之后(对于所有这些)。

我的问题

我的理解是否正确,我们什么时候应该使用哪个?还有,什么时候会有区别?

recyclerview:1.2.0-alpha02 引入了 MergeAdapter 已重命名为 ConcatAdapterrecyclerview:1.2.0-alpha04.
这个 RecyclerView Adapter 可以线性组合多个适配器

类似于:

FirstAdapter adapter1 = ...;
SecondAdapter adapter2 = ...;
ConcatAdapter merged = new ConcatAdapter(adapter1, adapter2);
recyclerView.setAdapter(mergedAdapter);

作为此更改的一部分,方法 getAdapterPosition() was deprecated because the name is confusing when adapters nest other adapters. Now you should use the method getBindingAdapterPosition() returns 在 特定适配器 (bindingAdapter) 中的位置。

同时查看RecyclerView.ViewHolder的源代码:

    @Deprecated
    public final int getAdapterPosition() {
        return getBindingAdapterPosition();
    }

取而代之的方法是getAbsoluteAdapterPosition() returns 项目相对于整个 RecyclerView 的适配器位置。如果您使用的是 ConcatAdapter,它是 ConcatAdapter 中的位置,而不是单个 bindingAdapter 中的位置。

仅举一个带有 2 个适配器的示例:

official blog post 中提供了更多详细信息。