6

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.

casolorz
  • 8,486
  • 19
  • 93
  • 200

2 Answers2

1

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.

yigit
  • 37,683
  • 13
  • 72
  • 58
0

This doesn't appear to be an issue on the new version of the support library (22.1.0).

casolorz
  • 8,486
  • 19
  • 93
  • 200