Counting listView items error

2019-06-06 10:07发布

问题:

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?

回答1:

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();


回答2:

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++;  
             }
         }


回答3:

Use this .It helps mine

String CountListRowNo= String.valueOf(+ListviewObj.getAdapter().getCount());