sky’s 雑記

主にAndroidとサーバーサイドの技術について記事を書きます

ViewPagerからViewPager2に移行するときのちょっとした罠

ちゃんとした記事を書きたいけど投稿しないよりマシなので小ネタ投稿

ViewPagerを0以外のpositionで起動したいときに以下のようにすると思う.

view_pager.currentItem = 1

内部的にはsetCurrentItemInternalsmoothScrollという値にfalseが渡っていてこれが渡っているとアニメーションなしでViewPagerのpositionが変わる.

public void setCurrentItem(int item) {
        mPopulatePending = false;
        setCurrentItemInternal(item, !mFirstLayout, false);
    }

    /**
     * Set the currently selected page.
     *
     * @param item Item index to select
     * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately
     */
    public void setCurrentItem(int item, boolean smoothScroll) {
        mPopulatePending = false;
        setCurrentItemInternal(item, smoothScroll, false);
    }

https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:viewpager/viewpager/src/main/java/androidx/viewpager/widget/ViewPager.java

ViewPager2でも同じようなことができるが実はこう書くとViewPagerと違う挙動になる.

view_pager2.currentItem = 1

内部的にはsmoothScrollにtrueが渡るので謎にanimationがかかったりpositionが移動しなかったりする.

 public void setCurrentItem(int item) {
        setCurrentItem(item, true);
    }

    /**
     * Set the currently selected page. If {@code smoothScroll = true}, will perform a smooth
     * animation from the current item to the new item. Silently ignored if the adapter is not set
     * or empty. Clamps item to the bounds of the adapter.
     *
     * @param item Item index to select
     * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately
     */
    public void setCurrentItem(int item, boolean smoothScroll) {
        if (isFakeDragging()) {
            throw new IllegalStateException("Cannot change current item when ViewPager2 is fake "
                    + "dragging");
        }
        setCurrentItemInternal(item, smoothScroll);
    }

https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:viewpager2/viewpager2/src/main/java/androidx/viewpager2/widget/ViewPager2.java

ViewPagerのview_pager.currentItem = 1とViewPager2のview_pager.setCurrentItem(1, false)が同等ですという話でした.

以上!