Search code examples
androidlistviewonscrolllistener

How to get current view item in list view after scrolling




While scrolling listview, I want to get current view which is having a textview and an image.
Based on this I want to show starting letter of the first visible contact view item on top of list similar to our contact list.
I tried with the following, But this is giving invalid index after scrolling.

HomeContactView extends AppCompatActivity implements AbsListView.OnScrollListener

overided corresponding methods

 @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
final ListView listView = mainListView;
        int location = listView.getFirstVisiblePosition();
}

Through this I am not able to get the current focused view and its elements.How to achieve this? Any help is really appreciable.
enter image description here


Solution

  • I think your code is close to being correct. I would use the current parameter view and typecast it. And I check for the scrolling status (parameter scrollState). You want to avoid processing the ListView when user is still scrolling.

    Code example:

    @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
           if (scrollState == SCROLL_STATE_IDLE) {
              final ListView listView = (ListView) view;
              int location = listView.getFirstVisiblePosition();
    
              View firstView = listview.getChildAt(location);
            }
       }
    

    You can also override the other method, public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount). The benefit of this method is that you can get the firstVisibleItem as an integer type. I have used it and it is accurate.