wickerman87
wickerman87

Reputation: 1

How to get each menu item from a list view by position?

Let's say a list has 4 items, how can I get a view from each menu item of a list by position?

Upvotes: 0

Views: 1445

Answers (2)

Michael Bray
Michael Bray

Reputation: 15265

Unfortunately the items that are in the ListView are generally only those that are visible. You should iterate on the ListAdapter instead.

For example, in some of my code, I have this:

    SimpleCursorAdapter adapter = (SimpleCursorAdapter) this.getListAdapter();
    int iNum = adapter.getCount();
    for(int i=0; i<iNum; i++) 
    {
        Cursor c = (Cursor) adapter.getItem(i);

        // Now you can pull data from the cursor object,
        // if that's what you used to create the adapter to start with
    }

EDIT: In response to jeffamaphone's comments, here's something else... if you are trying to work with each UI element then getChildAt is certainly more appropriate as it returns the View for the sub-item, but in general you can still only work with those that are visible at the time. If that's all you care about, then fine - just make sure you check for null when the call returns.

If you are trying to implement something like I was - a "Select All / Select None / Invert Selection" type of feature for a list that might exceed the screen, then you are much better off to make the changes in the Adapter, or have an external array (if as in my case, there was nowhere in the adapter to make the chagne), and then call notifyDataSetChanged() on the List Adapter. For example, my "Invert" feature has code like this:

    case R.id.selectInvertLedgerItems:
        for(int i=0; i<ItemChecked.length; i++)
        {
            ItemChecked[i] = !ItemChecked[i];
        }
        la.notifyDataSetChanged();
        RecalculateTotalSelected();
        break;

Note that in my case, I am also using a custom ListView sub-item, using adapter.setViewBinder(this); and a custom setViewValue(...) function.

Furthermore if I recall correctly, I don't think that the "position" in the list is necessarily the same as the "position" in the adapter... it is again based more on the position in the list. Thus, even though you are wanting the "50th" item on the list, if it is the first visible, getChildAt(50) won't return what you are expecting. I think you can use ListView.getFirstVisiblePosition() to account and adjust.

Upvotes: 1

Rahul Choudhary
Rahul Choudhary

Reputation: 3809

See here, this question answers the similar problem you mentioned here

In an android ListView, how can I iterate/manipulte all the child views, not just the visible ones?

Upvotes: 0

Related Questions