Android: Getting a count of the visible children in a listview

女生的网名这么多〃 提交于 2019-12-29 04:15:06

问题


Is there are way to get a count of the number of visible listview children?

I have a listview with info linked to a database that can change at any time. When the database is changed, I send out a broadcast notifying the ui class handling the list view. The child element relating to the changed data is then updated. I am achieving this by giving each listview item a tag, and then iterating over the listviews to find the row matching the tag from the broadcast.

I want to only iterate over the visible children. There is no need for me to manually update views that are not visible, as they will reflect the new data when they are created. I currently iterate from listView.getfirstVisiblePosition() to listView.getChildCount(). This is better than nothing, as I don't examine rows above the visible rows, but I don't want to examine the rows below them either.

I checked the android developers listView page and didn't find anything. Anyone know of a way I can get the count of visible children?

Thanks!


回答1:


listView.getLastVisiblePosition(), is this what you are looking for? if not, Iteration through child views...

int count = 0;

for (int i = 0; i <= listView.getLastVisiblePosition(); i++)
{
    if (listView.getChildAt(i) != null)
    {
        count++;  // saying that view that counts is the one that is not null, 
                  // because sometimes you have partially visible items....
    }
}



回答2:


This is a quick way to get visible children count:

int visibleChildCount = (listView1.getLastVisiblePosition() - listView1.getFirstVisiblePosition()) + 1;



回答3:


In reference to greg7gkb's comment above - just wanted to point out in case anyone is using this that it will make your count off by one. It should be

(listView1.getLastVisiblePosition() - listView1.getFirstVisiblePosition()) + 1

So, if the last visible was 8 and the first visible was 5, you would have (8-5)+1 = 4 showing:5,6,7, and 8.

It looks like A. Abiri got it right below.



来源:https://stackoverflow.com/questions/6740089/android-getting-a-count-of-the-visible-children-in-a-listview

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