1

Recently I came across a method to reverse the data in the listview which is:

getItem(getCount() - getPosition() - 1)

Reference to: Display new items at the top of a ListView

How does this formula work actually?

For example I have a set of data which contains:

a, b, c , d, e which have positions 1. 2, 3 , 4, 5 respectively.

Thus, the getCount() = 5,

Using the formula above the positions are:

getCount() - getPosition() - 1

a = 5 - 1 -1 = 3
b = 5 - 2 - 1 = 2
c = 5 - 3 - 1 = 1
d = 5- 4 - 1 = 0
e = 5 - 5 - 1 = -1

Based on these calculations, how do the data in the listview gets a reverse order?

The result that I get in the listiview after using the method are:

e, d, c, b, a.

Thank you.

Community
  • 1
  • 1
Mei Yi
  • 341
  • 3
  • 14

1 Answers1

2
a = 5 - 0 -1 = 4
b = 5 - 1 - 1 = 3
c = 5 - 2 - 1 = 2
d = 5- 3 - 1 = 1
e = 5 - 4 - 1 = 0

The position of the item is start from 0, not 1. So start from 0 it will display e,d,c,b,a. That's how the formula works.

cw fei
  • 1,534
  • 1
  • 15
  • 33