Counting listView items error

2019-06-06 09:44发布

I am trying to count listView items. Im using this code:

int count=0;
ListView listView = (ListView) findViewById(R.id.listView1);
 for(int i = 0; i  <= listView.getLastVisiblePosition(); i++)
         {
             if(listView.getChildAt(i)!= null)
             {
                 count++;  
             }
         }

Toast.makeText(getApplicationContext(), String.valueOf(count), Toast.LENGTH_SHORT).show();

Why the COUNT variable value is always 0, when listView display some records?

3条回答
Juvenile、少年°
2楼-- · 2019-06-06 10:20

Use this .It helps mine

String CountListRowNo= String.valueOf(+ListviewObj.getAdapter().getCount());
查看更多
beautiful°
3楼-- · 2019-06-06 10:33

If you are looking for count of all ListView items, you can use this call (make sure adapter is set):

listView.getCount();

If what you want is count of visible items, try this (works only for visible ListView):

listView.getLastVisiblePosition()-listView.getFirstVisiblePosition();
查看更多
太酷不给撩
4楼-- · 2019-06-06 10:33

Let me explain the reason.. You've just get the listview like this

ListView listView = (ListView) findViewById(R.id.listView1);

so listview has no elements and then you are tring to get the last visible postion by using listView.getLastVisiblePosition() it always returns zero because your listview hasn't yet bind with any adapter, i.e your listview is empty at the time your are getting the last visible position try to place this code after binding Adapter to the listview

for(int i = 0; i  <= listView.getLastVisiblePosition(); i++)
         {
             if(listView.getChildAt(i)!= null)
             {
                 count++;  
             }
         }
查看更多
登录 后发表回答