14

I noticed today that the PagerAdapter gets called a large amount times. I counted 393 when scrolling pages slowly. I saw this question but it didn't really provide me with a good answer.

  1. Is this normal behaviour
  2. If so, why is it that the getCount method is called so often?

Just to be clear, I am looking for a more extensive answer then the one in the provided question. I do also realize that I need to keep it as fast and that I have no control over how it is called, but that is not the question here.

Community
  • 1
  • 1
Qw4z1
  • 2,949
  • 1
  • 22
  • 35
  • When you read the source code to `ViewPager`, to find the answers to your questions, what did you learn? – CommonsWare Jan 19 '13 at 13:44
  • @CommonsWare I learned that it is used in several places. OnTouchEvent in particular. I am guessing that this is where it gets called every time I move the pager. Is this correct? – Qw4z1 Jan 19 '13 at 15:01
  • 3
    I haven't looked at `ViewPager` in this area. If `getCount()` is called on every touch event, though, that would certainly explain the high call count. – CommonsWare Jan 19 '13 at 15:05
  • @Qw4z1 i am also facing the same problem. in my case onmeasure is getting called many times which in turn calls populate() – manjusg Jan 24 '13 at 14:48

1 Answers1

5

As you concluded it is used a lot in onTouchEvent. OnTouchEvent is called whenever you interact with the screen, meaning touch move and release events. Moving just one pixel would result in a potential call to this method.

There is not much more to explain, it is just the way it is implemented. Usually adapter.getCount is implemented with something like List.getSize or Cursor.getCount. And has almost zero overhead. If this is a problem, optimize you ListAdapter.getCount method, cache the count or something like that. Only do complex stuff in there when needed and cache the result until it becomes invalid.

nickmartens1980
  • 1,583
  • 13
  • 23