【Android基础】TabLayout+ViewPager2+Fragment切换问题

问题点:

TabLayout+ViewPager2+Fragment 是我们常用的组合,但点击TabLayout的item时,ViewPager2默认的切换方式是滑动到指定item的Fragment,如果前后两个tab间隔了多个tab,那将滑过多个Fragment。

目标:

点击TabLayout的item,直接硬切换Fragment,同时兼备ViewPager可滑动切换效果。

尝试1:

找到关联 TabLayout 和 ViewPager 的工具类 TabLayoutMediator,可以看到是有待smoothScroll参数的构造函数,而这个参数在 TabLayout 的 ViewPagerOnTabSelectedListener监听中控制ViewPager的切换方式,看上去效果跟我们想要的类似,于是试一试:

new TabLayoutMediator(
	mTablayout,
	mViewPager,
	true,
	false,
	(tab, position) -> {
	
	}).attach();

运行后发现:点击 TabLayout 的 item 确实实现了硬切换 Fragment,但是滑动 ViewPager 时, TabLayout 的指示器无法跑到正确的标题下方,达不到我们想要的效果。

尝试2:(推荐)

自定义 TabLayoutMediator ,尝试在 ViewPager 的滑动监听器 TabLayoutOnPageChangeCallback 里设置自己的切换模式。

  • 首先,新建一个 CommonTabLayoutMediator 类,将 TabLayoutMediator 代码完整复制到类中,处理好引用。
  • 然后,找到 TabLayoutOnPageChangeCallback 的 onPageScrollStateChanged 方法,新增代码如下:
if (state == SCROLL_STATE_DRAGGING) {
    smoothScroll = true;
} else if (state == SCROLL_STATE_IDLE) {
    smoothScroll = false;
}
  • 接着,利用反射调用处理TabLayout中无法调用的两个方法:

注意,这两个方法很重要,如果不调用,会出现在滑动ViewPager到一半时目,TabLayout的目标item的指示器会闪现!

//原方法无法调用updateViewPagerScrollState,利用反射调用
try {
	TabLayout tabLayout = tabLayoutRef.get();
	if (tabLayout != null) {
		Method method = TabLayout.class.getDeclaredMethod("updateViewPagerScrollState", int.class);
		method.setAccessible(true);
		method.invoke(tabLayout, scrollState);
	}
}catch (Exception e){
	LogUtils.e(TAG, e.getMessage());
}
//原方法无法调用setScrollPosition,利用反射调用
try {
	Method method = TabLayout.class.getDeclaredMethod("setScrollPosition", int.class, float.class, boolean.class, boolean.class,boolean.class);
	method.setAccessible(true);
	method.invoke(tabLayout, position, positionOffset, updateText, updateIndicator, false);
}catch (Exception e){
	LogUtils.e(TAG, e.getMessage());
	tabLayout.setScrollPosition(position, positionOffset, updateText, updateIndicator);
}
  • 最后,用自定义的 CommonTabLayoutMediator 替换 TabLayoutMediator:
new CommonTabLayoutMediator(
	mTablayout, 
	mViewPager,
	(tab, position) -> {
		
	}).attach();

贴上 CommonTabLayoutMediator 完整代码,尽管拿去吧~

import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_DRAGGING;
import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_IDLE;
import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_SETTLING;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;


public class CommonTabLayoutMediator {

    private static final String TAG = "CommonTabLayoutMediator";

    private TabLayout tabLayout;
    private ViewPager2 viewPager;
    private boolean autoRefresh;
    private static boolean smoothScroll;
    private TabConfigurationStrategy tabConfigurationStrategy;
    @Nullable
    private RecyclerView.Adapter<?> adapter;
    private boolean attached;

    @Nullable
    private TabLayoutOnPageChangeCallback onPageChangeCallback;
    @Nullable
    private TabLayout.OnTabSelectedListener onTabSelectedListener;
    @Nullable
    private RecyclerView.AdapterDataObserver pagerAdapterObserver;

    /**
     * A callback interface that must be implemented to set the text and styling of newly created
     * tabs.
     */
    public interface TabConfigurationStrategy {
        /**
         * Called to configure the tab for the page at the specified position. Typically calls {@link
         * TabLayout.Tab#setText(CharSequence)}, but any form of styling can be applied.
         *
         * @param tab      The Tab which should be configured to represent the title of the item at the given
         *                 position in the data set.
         * @param position The position of the item within the adapter's data set.
         */
        void onConfigureTab(@NonNull TabLayout.Tab tab, int position);
    }

    public CommonTabLayoutMediator(
            @NonNull TabLayout tabLayout,
            @NonNull ViewPager2 viewPager,
            @NonNull TabConfigurationStrategy tabConfigurationStrategy) {
        this(tabLayout, viewPager, /* autoRefresh= */ true, tabConfigurationStrategy);
    }

    public CommonTabLayoutMediator(
            @NonNull TabLayout tabLayout,
            @NonNull ViewPager2 viewPager,
            boolean autoRefresh,
            @NonNull TabConfigurationStrategy tabConfigurationStrategy) {
        this(tabLayout, viewPager, autoRefresh, /* smoothScroll= */ false, tabConfigurationStrategy);
    }

    public CommonTabLayoutMediator(
            @NonNull TabLayout tabLayout,
            @NonNull ViewPager2 viewPager,
            boolean autoRefresh,
            boolean smoothScroll,
            @NonNull TabConfigurationStrategy tabConfigurationStrategy) {
        this.tabLayout = tabLayout;
        this.viewPager = viewPager;
        this.autoRefresh = autoRefresh;
        CommonTabLayoutMediator.smoothScroll = smoothScroll;
        this.tabConfigurationStrategy = tabConfigurationStrategy;
    }

    /**
     * Link the TabLayout and the ViewPager2 together. Must be called after ViewPager2 has an adapter
     * set. To be called on a new instance of TabLayoutMediator or if the ViewPager2's adapter
     * changes.
     *
     * @throws IllegalStateException If the mediator is already attached, or the ViewPager2 has no
     *                               adapter.
     */
    public void attach() {
        if (attached) {
            throw new IllegalStateException("TabLayoutMediator is already attached");
        }
        adapter = viewPager.getAdapter();
        if (adapter == null) {
            throw new IllegalStateException(
                    "TabLayoutMediator attached before ViewPager2 has an " + "adapter");
        }
        attached = true;

        // Add our custom OnPageChangeCallback to the ViewPager
        onPageChangeCallback = new TabLayoutOnPageChangeCallback(tabLayout);
        viewPager.registerOnPageChangeCallback(onPageChangeCallback);

        // Now we'll add a tab selected listener to set ViewPager's current item
        onTabSelectedListener = new ViewPagerOnTabSelectedListener(viewPager);
        tabLayout.addOnTabSelectedListener(onTabSelectedListener);

        // Now we'll populate ourselves from the pager adapter, adding an observer if
        // autoRefresh is enabled
        if (autoRefresh) {
            // Register our observer on the new adapter
            pagerAdapterObserver = new PagerAdapterObserver();
            adapter.registerAdapterDataObserver(pagerAdapterObserver);
        }

        populateTabsFromPagerAdapter();

        // Now update the scroll position to match the ViewPager's current item
        tabLayout.setScrollPosition(viewPager.getCurrentItem(), 0f, true);
    }

    /**
     * Unlink the TabLayout and the ViewPager. To be called on a stale TabLayoutMediator if a new one
     * is instantiated, to prevent holding on to a view that should be garbage collected. Also to be
     * called before {@link #attach()} when a ViewPager2's adapter is changed.
     */
    public void detach() {
        if (autoRefresh && adapter != null) {
            adapter.unregisterAdapterDataObserver(pagerAdapterObserver);
            pagerAdapterObserver = null;
        }
        tabLayout.removeOnTabSelectedListener(onTabSelectedListener);
        viewPager.unregisterOnPageChangeCallback(onPageChangeCallback);
        onTabSelectedListener = null;
        onPageChangeCallback = null;
        adapter = null;
        attached = false;
    }

    /**
     * Returns whether the {@link TabLayout} and the {@link ViewPager2} are linked together.
     */
    public boolean isAttached() {
        return attached;
    }

    @SuppressWarnings("WeakerAccess")
    void populateTabsFromPagerAdapter() {
        tabLayout.removeAllTabs();

        if (adapter != null) {
            int adapterCount = adapter.getItemCount();
            for (int i = 0; i < adapterCount; i++) {
                TabLayout.Tab tab = tabLayout.newTab();
                tabConfigurationStrategy.onConfigureTab(tab, i);
                tabLayout.addTab(tab, false);
            }
            // Make sure we reflect the currently set ViewPager item
            if (adapterCount > 0) {
                int lastItem = tabLayout.getTabCount() - 1;
                int currItem = Math.min(viewPager.getCurrentItem(), lastItem);
                if (currItem != tabLayout.getSelectedTabPosition()) {
                    tabLayout.selectTab(tabLayout.getTabAt(currItem));
                }
            }
        }
    }

    /**
     * A {@link ViewPager2.OnPageChangeCallback} class which contains the necessary calls back to the
     * provided {@link TabLayout} so that the tab position is kept in sync.
     *
     * <p>This class stores the provided TabLayout weakly, meaning that you can use {@link
     * ViewPager2#registerOnPageChangeCallback(ViewPager2.OnPageChangeCallback)} without removing the
     * callback and not cause a leak.
     */
    private static class TabLayoutOnPageChangeCallback extends ViewPager2.OnPageChangeCallback {
        @NonNull
        private final WeakReference<TabLayout> tabLayoutRef;
        private int previousScrollState;
        private int scrollState;

        TabLayoutOnPageChangeCallback(TabLayout tabLayout) {
            tabLayoutRef = new WeakReference<>(tabLayout);
            reset();
        }

        @Override
        public void onPageScrollStateChanged(final int state) {
            previousScrollState = scrollState;
            scrollState = state;
            //原方法无法调用updateViewPagerScrollState,利用反射调用
            try {
                TabLayout tabLayout = tabLayoutRef.get();
                if (tabLayout != null) {
                    Method method = TabLayout.class.getDeclaredMethod("updateViewPagerScrollState", int.class);
                    method.setAccessible(true);
                    method.invoke(tabLayout, scrollState);
                }
            }catch (Exception e){
                
            }
            if (state == SCROLL_STATE_DRAGGING) {
                smoothScroll = true;
            } else if (state == SCROLL_STATE_IDLE) {
                smoothScroll = false;
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            TabLayout tabLayout = tabLayoutRef.get();
            if (tabLayout != null) {
                // Only update the text selection if we're not settling, or we are settling after
                // being dragged
                boolean updateText =
                        scrollState != SCROLL_STATE_SETTLING || previousScrollState == SCROLL_STATE_DRAGGING;
                // Update the indicator if we're not settling after being idle. This is caused
                // from a setCurrentItem() call and will be handled by an animation from
                // onPageSelected() instead.
                boolean updateIndicator =
                        !(scrollState == SCROLL_STATE_SETTLING && previousScrollState == SCROLL_STATE_IDLE);
                //原方法无法调用setScrollPosition,利用反射调用
                try {
                    Method method = TabLayout.class.getDeclaredMethod("setScrollPosition", int.class, float.class, boolean.class, boolean.class,boolean.class);
                    method.setAccessible(true);
                    method.invoke(tabLayout, position, positionOffset, updateText, updateIndicator, false);
                }catch (Exception e){
                    tabLayout.setScrollPosition(position, positionOffset, updateText, updateIndicator);
                }
            }
        }

        @Override
        public void onPageSelected(final int position) {
            TabLayout tabLayout = tabLayoutRef.get();
            if (tabLayout != null
                    && tabLayout.getSelectedTabPosition() != position
                    && position < tabLayout.getTabCount()) {
                // Select the tab, only updating the indicator if we're not being dragged/settled
                // (since onPageScrolled will handle that).
                boolean updateIndicator =
                        scrollState == SCROLL_STATE_IDLE
                                || (scrollState == SCROLL_STATE_SETTLING
                                && previousScrollState == SCROLL_STATE_IDLE);
                tabLayout.selectTab(tabLayout.getTabAt(position), updateIndicator);
            }
        }

        void reset() {
            previousScrollState = scrollState = SCROLL_STATE_IDLE;
        }
    }

    /**
     * A {@link TabLayout.OnTabSelectedListener} class which contains the necessary calls back to the
     * provided {@link ViewPager2} so that the tab position is kept in sync.
     */
    private static class ViewPagerOnTabSelectedListener implements TabLayout.OnTabSelectedListener {
        private final ViewPager2 viewPager;
//        private final boolean smoothScroll;

        ViewPagerOnTabSelectedListener(ViewPager2 viewPager) {
            this.viewPager = viewPager;
        }

        @Override
        public void onTabSelected(@NonNull TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition(), smoothScroll);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            // No-op
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            // No-op
        }
    }

    private class PagerAdapterObserver extends RecyclerView.AdapterDataObserver {
        PagerAdapterObserver() {
        }

        @Override
        public void onChanged() {
            populateTabsFromPagerAdapter();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            populateTabsFromPagerAdapter();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
            populateTabsFromPagerAdapter();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            populateTabsFromPagerAdapter();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            populateTabsFromPagerAdapter();
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            populateTabsFromPagerAdapter();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值