GetItem vs getItemAtPosition

There are two ways to get the selected list item.

  • list.getAdapter().getItem(position);
  • list.getItemAtPosition(position)

My question is: which one is preferred?

I have seen people use both.

+4
source share
3 answers

You can use the one you want. getItemAtPosition(position) basically makes the adapter call with getItem(position) , it's the same thing.

+3
source

Here is the implementation of getItemAtPosition() from the ListView source code.

 public Object getItemAtPosition(int position) { T adapter = getAdapter(); return (adapter == null || position < 0) ? null : adapter.getItem(position); } 

So basically they are the same.

+2
source

Other answers are incorrect, there is one big difference.

When you add a title to the ListView, the ListView wraps the adapter in the HeaderViewListAdapter. The HeaderViewListAdapter job translates position to accept headers.

For example, if you added one header, position 1 corresponds to the base adapter position 0 . If you tried to use adapter.getItem (position), it will actually return you the second element in the adapter.

If you added a title, you should use listView.getItemAtPosition (position).

+1
source

Source: https://habr.com/ru/post/1411002/


All Articles