Search code examples
javaandroidandroid-recyclerviewandroid-listviewandroid-gridview

How to get the item position in a ListView and GridView outside the adapter?


I'm trying to get a View position through his view hierarchy.

When I have a RecyclerView, for get the current view position I do:

if(view.getParent() instanceof RecyclerView){ 
  RecyclerView rv = (RecyclerView)view.getParent();
  if(rv.getLayoutManager()!=null) {
     position = rv.getLayoutManager().getPosition(view);
  }
}

But when a ListView or GridView appears, I'm not able to get a Layout Manager to get the position of the view. The idea is to make it in a generic way, without knowing the Custom Adapter the view has.

I have tried to get the position through the ListView and GridView adapter but I dont see any method that do that.

Someone can help me? Thank you a lot!


Solution

  • I have found a solution:

    if(view.getParent() instanceof ViewGroup) {
       position = ((ViewGroup)view.getParent()).indexOfChild(view);
    }