[英]Android - holder returning null from recyclerView adapter item position
I want to get the view from a given item position in my recyclerView, but the holder is always coming null and I cant figure out why. 我想从我的recyclerView中的给定项目位置获取视图,但是持有人总是空的,我不知道为什么。
Rect toRect = new Rect();
selectedPostTagsAdapter.addPostTag(postTag);
selectedPostTagsAdapter.notifyDataSetChanged();
for (int i = 0; i < selectedPostTagsAdapter.getItemCount(); i++) {
RecyclerView.ViewHolder holder = rvSelectedPostTags.findViewHolderForItemId(selectedPostTagsAdapter.getItemId(i));
if (holder != null) {
View viewX = holder.itemView;
viewX.getGlobalVisibleRect(toRect);
}
There are two reasons that RecyclerView.findViewHolderForItemId()
might return null. RecyclerView.findViewHolderForItemId()
可能返回null的原因有两个。
First, it will always return null if your RecyclerView
does not have stable ids. 首先,如果您的
RecyclerView
没有稳定的ID,它将始终返回null。 You can call rvSelectedPostTags.setHasStableIds(true)
to turns this feature on. 您可以调用
rvSelectedPostTags.setHasStableIds(true)
启用此功能。 Note, however, that you actually have to have logically-stable ids if you want to use this. 但是请注意,如果要使用它,则实际上必须具有逻辑上稳定的ID。 All that means is that a given data item should always return the same id, regardless of its position.
这意味着给定的数据项无论其位置如何都应始终返回相同的id。
Second, it will return null if you pass the id of an item that is not currently laid out inside the RecyclerView
. 其次,如果您传递
RecyclerView
内当前未布置的商品的ID,它将返回null。 So if you can currently see items #5-#12, but you want the ViewHolder
for #200, it's not going to work. 因此,如果您当前可以看到项目#5-#12,但是您希望使用#200的
ViewHolder
,则它将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.