ViewPager setCurrentItem freezes UI thread

别说谁变了你拦得住时间么 提交于 2020-01-02 03:01:09

问题


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?


回答1:


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.




回答2:


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);
        }
 }



回答3:


i have this issue. add below method to custom viewPager and use this.

private void setupCurrentItem(int cur)
    {
        try
        {
            Class<?> viewpager = ViewPager.class;
            Field mCurItemField = viewpager.getDeclaredField("mCurItem");
            mCurItemField.setAccessible(true);
            mCurItemField.set(this, cur);
        }
        catch (Exception ignored) {}
    }


setupCurrentItem(100);
setCurrentItem(100, false);


来源:https://stackoverflow.com/questions/18740916/viewpager-setcurrentitem-freezes-ui-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!