ADIT
ADIT

Reputation: 2428

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

Upvotes: 7

Views: 48110

Answers (2)

Debarati
Debarati

Reputation: 3286

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.

Upvotes: 3

Khawar
Khawar

Reputation: 5227

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

Upvotes: 4

Related Questions