Get all ListView items(rows)
Asked Answered
H

4

10

How may I get all children of an item of ListView ?
There are methods to get child at position but I was not able to find any method which returns collection of all children in an item of ListView.

Update : I just found out that I need ListView items(rows) instead. How may I achieve this ?
What I am doing is, comparing the selected ListView item with all items.

Haslett answered 13/9, 2014 at 9:22 Comment(1)
Not entirely sure why you are doing this, but wouldn't it be better to just pull all the data direct from the Adapter? Instead of pulling views from the ListView.Carcassonne
M
7

You get all list item from list adapter through iteration as below

for (int i=0;i<adapter.getCount();i++){
     adapter.getItem(i);
}

Update : You can compare specific item using index with list adapter all items as below :

for (int i=0;i<adapter.getCount();i++){
    if(adapter.get(selectedIndex)==adapter.getItem(i)){
       // TODO : write code here item match 
       break; // after match is good practice to break loop instead compare rest of item even match
    }
}
Menswear answered 13/9, 2014 at 9:25 Comment(0)
D
4

Use this method to get all insight and out-sight view of list view:

for ( int i = 0 ; i < listView.getCount() ; i++){
    View v = getViewByPosition(i,listView);
}

public View getViewByPosition(int position, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition =firstListItemPosition + listView.getChildCount() - 1;

    if (position < firstListItemPosition || position > lastListItemPosition ) {
        return listView.getAdapter().getView(position, listView.getChildAt(position), listView);
    } else {
        final int childIndex = position - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}
Decima answered 13/9, 2014 at 9:54 Comment(0)
C
2

I guess if your items in the ListView are of type ViewGroup you could do the following

ArrayList<View> children = new ArrayList<View>();
for (int i = item.getChildCount() - 1 ; i>=0; i--) {
    children.add(item.getChildAt(i));
}
Chemesh answered 13/9, 2014 at 11:16 Comment(1)
I'm getting a bug where item.getChildCount() < adapter.getCount(). I need to grab one item and color its background, and getChildAt apparently only returns visible children, if there are too many itemsDepartmentalism
K
1

May be you are looking for something like this. You need to have access to the rootView from which you can get the child views. onItemSelected is only used as it gives the rootview of clicked position.

public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
ImageView imgView = view.findViewById(R.id.myImageView);//your imageview that is inflated inside getView() of adapter
//similarly for other views 
}
Knock answered 13/9, 2014 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.