ViewPagerからViewPager2に移行するときのちょっとした罠
ちゃんとした記事を書きたいけど投稿しないよりマシなので小ネタ投稿
ViewPagerを0以外のpositionで起動したいときに以下のようにすると思う.
view_pager.currentItem = 1
内部的にはsetCurrentItemInternal
のsmoothScroll
という値に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); }
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); }
ViewPagerのview_pager.currentItem = 1
とViewPager2のview_pager.setCurrentItem(1, false)
が同等ですという話でした.
以上!