Search code examples
androidandroid-listviewandroid-adapter

Get the Margin top of a clicked item in a listview


I have a problem with the setSelection of a Listview that I fill with Adapter.

I use setSelection when I return to a list of items, after I have clicked on an item to see the detail (view2)or edit its information, and then also edit what I show in the list.

Theoretically setSelection could work well for me, because before I access the detail page (view2) I take and store the number of the first visible item in the list, which I then return to setSelection when I return.

What I don't like is that I have an element at the beginning of the list that isn't all hidden (exited from the list) is still considered first even if by a few pixels, and so when I return instead of seeing the first element I see, I see the one that was almost completely gone with the scroll.

I would like to know if there is a method for precisely taking the co-ordinates of an item within the listview.

For example if when I click on the item I can take the top margin and then when I return to the list if I can use another method to give that item the top margin. If it can't be done for the clicked item but for the first visible item in the listview as well, I think it would work fine.

do you have any suggestions for taking the margin or maybe some other tips to solve the problem

Thanks


Solution

  • You can take the margin of the first Item like this

            firstVisible = list.firstVisiblePosition
            marginfirstVisible = list.getChildAt(0).top
    

    and then when you recreate the list you add this

            list.setSelectionFromTop(firstVisible,marginfirstVisible)