For some reason I'm not able to use holder.getAdapterPosition()
because it always returns -1 but holder.getLayoutPosition()
returns a 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 bit 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 is happening is that the ViewParent is null. Any idea why that might be?
Other than that my recycler is working just fine.
Thanks.
A ViewHolder describes an item view and metadata about its place within the RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive findViewById results.
bindViewHolder. This method internally calls onBindViewHolder to update the ViewHolder contents with the item at the given position and also sets up some private fields to be used by RecyclerView.
If parent is null, that means ViewHolder is not a child of RecyclerView thus we have not been tracking its position. Layout position is its latest position when it was laid out.
In the following releases, we'll extend the scope of getAdapterPosition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With