Search code examples
androidandroid-listviewscrollbarandroid-arrayadapternotifydatasetchanged

Android: Detect if a ListView has the scrollbar (after setting new data)


I have an ArrayAdapter linked to a ListView.

mListView.setAdapter(mArrayAdapter);

Whenever I reset the ArrayList data to the ArrayAdapter:

mArrayAdapter.clear();
mArrayAdapter.addAll(mArrayList);
mArrayAdapter.notifyDataSetChanged()

the ListView gets correctly updated

however, if just after the above three lines, I call my custom method mListView.hasScrollbar() to detect whether the listview has a scrollbar or not, I get a null lastVisibleItem:

public boolean hasScrollbar() {
    View lastVisibleItem = (View) getChildAt(getChildCount() - 1);
    if (lastVisibleItem.getBottom()>=getHeight()) {
        return true;
    }
    return false;
}

does it mean that the listview is still refreshing?

My main question is:
how can I test if the listview has the scrollbar after resetting the adapter with new data?

thank you for any help!


Solution

  • Using getLastVisiblePosition / getFirstVisiblePosition is a valid method of detecting wether you have scrolling or not within the list view (aslong as you compare it to getCount() and do your math ofc). The problem you have as you already guess is that you are attempting to check out of sync. In order to sync your query when the adapter already filled your List Data and updated changes, you need to issue a post request to the list, which will stack that petition to the message queue of the adapter.

    yourAdapter.notifyDataSetChanged();
    yourAdapter.getListView().post(new Runnable() { 
        @Override public void run() { 
            //your code here        
        } 
    });
    

    Make sure to call that after notifySetDataChanged() of course. Because you want the list to update before the check.