Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is getCount called so many times in PagerAdapter?

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.

like image 921
Qw4z1 Avatar asked Jan 19 '13 06:01

Qw4z1


People also ask

What is the difference between PagerAdapter and Fragmentpageradapter?

The difference is that you can use Fragments inside a FragmentPageAdapter . If you want to have fragments that are going to be used in other parts of your code this is your Adapter. Otherwise if you only want to have code that isn't going to be reused, you can use PagerAdapter .

What the difference between ViewPager and ViewPager2?

ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .

What is PagerAdapter?

PagerAdapter supports data set changes. Data set changes must occur on the main thread and must end with a call to notifyDataSetChanged similar to AdapterView adapters derived from android. widget. BaseAdapter . A data set change may involve pages being added, removed, or changing position.

What is View Pager?

Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows. ViewPager is most often used in conjunction with android. app. Fragment , which is a convenient way to supply and manage the lifecycle of each page.


1 Answers

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.

like image 120
nickmartens1980 Avatar answered Oct 18 '22 15:10

nickmartens1980