Counting listView items error

…衆ロ難τιáo~ 提交于 2019-12-08 09:16:17

问题


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


来源:https://stackoverflow.com/questions/15185334/counting-listview-items-error

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