Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewHolder.getAdapterPosition() always returns -1

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.

like image 567
casolorz Avatar asked Mar 19 '15 22:03

casolorz


People also ask

What is the function of a ViewHolder?

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.

What is the use of onBindViewHolder in Android?

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.


1 Answers

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.

like image 105
yigit Avatar answered Oct 03 '22 09:10

yigit