I have a RecyclerView . In the layout for the item, there is an ImageView on which hangs onClick , which calls the corresponding method in the class in which this RecyclerView initialized. In the method argument, I get the View element that the user clicked on. I need to know the position of the item in which this element is located.

I looked at the documentation and there is a getChildAdapterPosition method. I gave it a view to get the number of the item in which it is located, but when I click on this item, the application just crashes.

What am I doing wrong?

Here is the code for the click handler method:

 public void onClickHandler(View view) { switch (view.getId()) { case R.id.status_img: if (view.getTag() instanceof Roll) { Roll roll = (Roll) view.getTag(); int recyclerPos = recyclerView.getChildAdapterPosition(view); } break; } } 
  • What adapter method is this clicker in? - pavlofff
  • 2
    Try this: position=recyclerView.findContainingViewHolder(view).getPosition(); - Andrey Mihalev
  • 3
    @AndreyMihalev if it is inside the adapter, then accessing the widget is an extremely unwise decision. If this is in activation, then you need to contact the getAdapterPosition() method of the holder, since getPosition() is deprecated, then the solution makes sense. - pavlofff
  • one
    @cheerful_weasel If the clicker is specified in the markup, then see the option as done in this answer . There for ListView , but the principle is clear, I think. - pavlofff
  • one
    @pavloff yes, really, already read about getPosition. Thank you, I will consider for the future. - Andrey Mihalev

1 answer 1

In the RecyclerView operation, for each element of the root View, the LayoutParams property of the type android.support.v7.widget.RecyclerView.LayoutParams is added to the View object, which has the mViewHolder parameter that contains service information about the View position in RecyclerView.

When using the getChildAdapterPosition (View) method, the following happens:

 ((android.support.v7.widget.RecyclerView.LayoutParams) view.getLayoutParams()).mViewHolder.getLayoutPosition(); 

Since the ImageView, which was hung onClick, is not the root View for the list item, the ImageView method getLayoutParams returns an object that cannot be cast to android.support.v7.widget.RecyclerView.LayoutParams. This causes a cast error and the application crash.

An example of how to best resolve the issue: http://whiteshieldsoftware.blogspot.ru/2016/01/recyclerview-6.html