Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager setCurrentItem freezes UI thread

I am using a ViewPager from Android support v13 and I'd like to scroll to a specific item using setCurrentItem(int), but when I try to scroll more than 2 pages the application freezes, and after a few seconds the system shows an ANR window.

I tried to increase the offscreen screen limit using setOffscreenPageLimit(2), that way it did not freeze when i tried to scroll 2 pages, but did the same for 3 pages.

My problem is that my fragments are pretty memory consuming so I would not like to have too much in memory. I used the same code with support library v4, but I had to update it to v13 to use NotificationCompat.Builder.addAction(int, CharSequence, PendingIntent).

Does any of you know what could be the problem, and what could be the solution?

like image 513
pshegger Avatar asked Sep 11 '13 12:09

pshegger


2 Answers

Is your adapter handling very large amounts of items? (very large > ~220 items)

ViewPager.populate(int) will loop from the current item position to N, which is the number of items in the adapter - so if you've set it to something large (such as Integer.MAX_VALUE) this will takes some time, but will eventually finish.

If this is your case, search for "endless pager" related questions, such as Endless ViewPager android, or limit the number of items to something that's reasonable for the main thread.

like image 127
duvduv Avatar answered Oct 05 '22 23:10

duvduv


I had the same issue. I used PagerAdapter for infinite scrolling.

public static final int INITIAL_OFFSET = 1000;
@Override
    public int getCount() {
        return Integer.MAX_VALUE / 2;
}

And started the ViewPager in this way:

viewPager.setCurrentItem(INITIAL_OFFSET);

So to get rid of the freezing I wrote small function:

private void movePagerToPosition(int position) {
        int current = viewPager.getCurrentItem();
        int sign = current > position ? -1: 1;
        while (viewPager.getCurrentItem() != position){
            viewPager.setCurrentItem(viewPager.getCurrentItem() + sign, true);
        }
 }
like image 30
yshahak Avatar answered Oct 05 '22 23:10

yshahak