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

天大地大妈咪最大 提交于 2020-01-14 10:42:50

问题


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!


回答1:


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.




回答2:


I think your question equals to "how to tell if list view contains items need to displayed on more than one screen"?

So my suggestion is to use listView.getFirstVisiblePosition() and getLastVisiblePosition() to tell it.



来源:https://stackoverflow.com/questions/20450765/android-detect-if-a-listview-has-the-scrollbar-after-setting-new-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!