Joseph_Marzbani
Joseph_Marzbani

Reputation: 1876

how to translate 'position' parameter in ArrayAdapter.getView() into an absolut index of underlying data?

Suppose we have a ListView that can display 5 item at a time. We have (for instance) 100 items to be showed by this ListView. When we scroll through this list, ListView calls ArrayAdapter.getView(int position, ...) to get new views.

The problem is that the parameter 'position' will never go beyond '5' since ListView in our example cannot display more than 5 items at a time. But when the user clicks an item, how on the earth am I supposed to know which member/index/position/... in ArrayAdapter this selected item represents?

Suppose we have scrolled down to see the following:


item 56

item 57

item 58

item 59

item 60

Now when the user clicks 'item 58', position parameter is equel to '2' while I want to get '58'. Likewise 'item 59' will set 'position' to '3', while I want '59'. What can I do?

Upvotes: 1

Views: 1680

Answers (3)

Margarita Litkevych
Margarita Litkevych

Reputation: 2136

Well, I created a sample application with a listview (basing on code from http://www.vogella.com/articles/AndroidListView/article.html in 1.5 chapter) and overrided getView method in adapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    System.out.println("getView " + String.valueOf(position));
    return super.getView(position, convertView, parent);
}

Then I ran the application and the output after scrolling (10 views per screen): 0...9 for first screen and then 10..19.

So parameter position GOES beyond views_number_per_screen in getView. See example code for activity: http://pastebin.com/tvKv8kBu

Upvotes: 1

Samuil Yanovski
Samuil Yanovski

Reputation: 2867

You could use ArrayAdapter.getItem() to get the item associated with the clicked view. In your case it would return the 58th item, which is current at position 2.

Upvotes: 1

Mikel
Mikel

Reputation: 1621

Create a custom adapter and override the getView method and set the real position in the tag of the view. That way if you use view.getTag() you get the real position of the element.

Upvotes: 0

Related Questions