简体   繁体   中英

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.

                        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.

First, it will always return null if your RecyclerView does not have stable ids. You can call rvSelectedPostTags.setHasStableIds(true) to turns this feature on. Note, however, that you actually have to have logically-stable ids if you want to use this. All that means is that a given data item should always return the same id, regardless of its position.

Second, it will return null if you pass the id of an item that is not currently laid out inside the RecyclerView . So if you can currently see items #5-#12, but you want the ViewHolder for #200, it's not going to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM