ViewHolder.getAdapterPosition () always returns -1

For some reason, I cannot use holder.getAdapterPosition() because it always returns -1, and holder.getLayoutPosition() returns the position just fine.

My onCreateViewHolder:

@Override

 public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.my_item, parent, false); ViewHolder vh = new ViewHolder(this, v); return vh; } 

My ViewHolder constructor:

 public ViewHolder(DirectoryListAdapter adapter, View linear) { super(linear); this.adapter = adapter; this.linear = (LinearLayout) linear; this.entryName = (TextView) linear.findViewById(R.id.item_name); this.entryImage = (ImageView) linear.findViewById(R.id.item_image); } 

I looked a little further, and getAdapterPosition looks like this:

  public final int getAdapterPosition() { final ViewParent parent = itemView.getParent(); if (!(parent instanceof RecyclerView)) { return -1; } final RecyclerView rv = (RecyclerView) parent; return rv.getAdapterPositionFor(this); } 

And basically what happens is that ViewParent is NULL. Any idea why this could be?

In addition, my processor is working fine.

Thanks.

+6
source share
2 answers

This is not a problem in the new version of the support library (22.1.0).

0
source

If parent is null, that means the ViewHolder is not a child of the RecyclerView, so we are not tracking its position. The layout location is its last position when it was laid out.

In future releases, we will expand the scope of getAdapterPosition.

+1
source

Source: https://habr.com/ru/post/984028/


All Articles