ViewPager setCurrentItem freezes UI thread

安稳与你 提交于 2019-12-05 05:12:51
duvduv

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.

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

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