Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a count of list items from Listview?

I'm using below code to travers my list it is working fine if List Items are visible.

If List is scrollable then non visible items are not accessing using this code. How to traverse all the list items which are visble + non visible items.

for(int i=0;i<list.getCount;i++)
{
   View v = list.getChildAt(i);
   TextView tv= (TextView) v.findViewById(R.id.item);
   Log.d("","ListItem :"+tv.getText());
}
like image 915
ADIT Avatar asked Feb 04 '11 06:02

ADIT


2 Answers

Here is how you can get your ListView in the Activity and traverse it.

ListView myList = getListView();
int count = myList.getCount();
for (int i = 0; i < count; i++) 
{
   ViewGroup row = (ViewGroup) myList.getChildAt(i);
   TextView tvTest = (TextView) row.findviewbyid(R.id.tvTestID);
    //  Get your controls from this ViewGroup and perform your task on them =)

}

I hope this will help

like image 151
Khawar Avatar answered Nov 08 '22 20:11

Khawar


Recently i did this thing. Suppose i want to invisible a button on a listItem. Then in the getView of the list adapter add that button in a global vector. like below.

 Button del_btn = viewCache.getFrame();
 view_vec.add(del_btn);

Here viewCache is a object of ViewCache class, which is sumthing like below -

   class ViewCache 
     {        

         private View baseView;     
         private Button button;


         public ViewCache(View baseView) 
         {       
             this.baseView = baseView;   
         }  

         public Button getButton() {
             if(button == null) {
                 button = (Button)   baseView.findViewById(R.id.DeleteChatFrndBtn);
             }
             return button;
         }
     }  


 //it is necessary sometimes because otherwise in some cases the list scroll is slow. 

Now you like to visible the listItem's button onClicking some other button. Then the code is like below -

 public void onClick(View v) {
    // TODO Auto-generated method stub

    switch(v.getId()) {

        case R.id.EditChatFrndBtn:
            length = view_vec.size();
            for(int i = 0; i < length; i++) {

                Button btn = (Button) view_vec.elementAt(i);
                btn.setVisibility(View.VISIBLE);

            }
            doneBtn.setVisibility(View.VISIBLE);
            editBtn.setVisibility(View.INVISIBLE);
            break;
     }
}

Instead of R.id.EditChatFrndBtn put your button id on clicking of which you will invisible/visible the listItem's button.

like image 40
Debarati Avatar answered Nov 08 '22 21:11

Debarati