当前位置:   article > 正文

android TabLayout+ViewPager2+Fragment关闭平滑滚动动画_smoothscroll=false

smoothscroll=false

abLayout+ViewPager2+Fragment 四个页面以上:当从第一页切换到第四页、会依次从二、三滚动到第四页。页面跨越越多个效果越明显,体验很不好,怎么关闭平滑滚动动画,而是点击tab后直接跳转到相应的页面呢?

        ViewPager的setCurrentItem(int item, boolean smoothScroll)方法smoothScroll=false可以直接跳转,我们可以自定义一个ViewPager重写改方法实现。

        但是ViewPager2是final类,只能另辟蹊径: 我想控制点击TabLayout 使ViewPager2滚动核心是通过TabLayoutMediator进行绑定,先看源码看有三个构造函数:

  1. public TabLayoutMediator(
  2. @NonNull TabLayout tabLayout,
  3. @NonNull ViewPager2 viewPager,
  4. @NonNull TabConfigurationStrategy tabConfigurationStrategy) {
  5. this(tabLayout, viewPager, /* autoRefresh= */ true, tabConfigurationStrategy);
  6. }
  7. public TabLayoutMediator(
  8. @NonNull TabLayout tabLayout,
  9. @NonNull ViewPager2 viewPager,
  10. boolean autoRefresh,
  11. @NonNull TabConfigurationStrategy tabConfigurationStrategy) {
  12. this(tabLayout, viewPager, autoRefresh, /* smoothScroll= */ true, tabConfigurationStrategy);
  13. }
  14. public TabLayoutMediator(
  15. @NonNull TabLayout tabLayout,
  16. @NonNull ViewPager2 viewPager,
  17. boolean autoRefresh,
  18. boolean smoothScroll,
  19. @NonNull TabConfigurationStrategy tabConfigurationStrategy) {
  20. this.tabLayout = tabLayout;
  21. this.viewPager = viewPager;
  22. this.autoRefresh = autoRefresh;
  23. this.smoothScroll = smoothScroll;
  24. this.tabConfigurationStrategy = tabConfigurationStrategy;
  25. }

可以看出第三个构造函数有smoothScroll入参,TabLayoutMediator类继续往下看这个参数是用来做什么的?

  1. public void attach() {
  2. if (attached) {
  3. throw new IllegalStateException("TabLayoutMediator is already attached");
  4. }
  5. ……
  6. // Now we'll add a tab selected listener to set ViewPager's current item
  7. onTabSelectedListener = new ViewPagerOnTabSelectedListener(viewPager, smoothScroll); // 在被这里传入监听器
  8. ……
  9. }
  10. // 再看看监听器里面的做了什么?
  11. @Override
  12. public void onTabSelected(@NonNull TabLayout.Tab tab) {
  13. viewPager.setCurrentItem(tab.getPosition(), smoothScroll);
  14. }
  15. /**
  16. *设置当前选定的页面。如果{@code smoothScroll=true},将执行平滑
  17. *从当前项目到新项目的动画。如果未设置适配器,则静默忽略
  18. *或者是空的。将项夹到适配器的边界。
  19. *
  20. *@param item要选择的项目索引
  21. *@param smoothScroll True可平滑滚动到新项目,false可立即转换
  22. */
  23. public void setCurrentItem(int item, boolean smoothScroll) {
  24. if (isFakeDragging()) {
  25. throw new IllegalStateException("Cannot change current item when ViewPager2 is fake "
  26. + "dragging");
  27. }
  28. setCurrentItemInternal(item, smoothScroll);
  29. }

所以我们可以使用第三个构造函数来关闭平滑滚动效果:

  1. TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(binding.tablayout, binding.viewPager2, true, false, (tab, position) -> {
  2. // 这里初始化Tab自定义
  3. tab.setCustomView(R.layout.custom_tab_view);
  4. });
  5. tabLayoutMediator.attach();

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/450039
推荐阅读
相关标签
  

闽ICP备14008679号