当前位置:  开发笔记 > Android > 正文

ViewPager addOnPageChangeListener不在同一个tabClick上工作

如何解决《ViewPageraddOnPageChangeListener不在同一个tabClick上工作》经验,为你挑选了1个好方法。



1> sonnet..:

原答案:

Android团队已经改变了一些关于TabLayout和ViewPager如何相互通信的事情.阅读文档.但事情并没有得到很好的解释.我在代码中包含了很多注释.我希望有所帮助.

final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
Adapter adapter = new Adapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);

// the tabs will get their titles from the adapter and get populated
tabLayout.setTabsFromPagerAdapter(adapter);

// this is done "so that the tab position is kept in sync"
// what it does is when you swipe the fragment in view pager, it updates the tabs
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

// without this listener the tabs would still get updated when fragments are swiped, but ....  (read the next comment)
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        Toast.makeText(MainActivity.this, "tabSelected:  " + tab.getText(), Toast.LENGTH_SHORT).show();
        // no where in the code it is defined what will happen when tab is tapped/selected by the user
        // this is why the following line is necessary
        // we need to manually set the correct fragment when a tab is selected/tapped
        // and this is the problem in your code
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        Toast.makeText(MainActivity.this, "tabReSelected:  " + tab.getText(), Toast.LENGTH_SHORT).show();

        // Reload your recyclerView here
    }
});

看看这个问题,如果你有任何其他问题.

编辑1:2015年12月

不是这个问题的解决方案,但总体上有帮助.

tabLayout.setupWithViewPager(viewPager);

这样,在选择选项卡时,您无需担心自己设置片段.tabLayout.setOnTabSelectedListener(..)在这种情况下不再需要.这是在引擎盖下处理的.当您不需要对选项卡进行过多控制时(例如,在选择/点击相同选项卡时重新加载片段),这非常有用.

更新:2018年5月

tabLayout.setTabsFromPagerAdapter(adapter);
tabLayout.setOnTabSelectedListener(...);

上述两个函数都已弃用.初始化viewpager + tablayout,如下所示:

viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager); // this will automatically bind tab clicks to viewpager fragments
viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabLayout))

// do additional tab clicks here
// no need to manually set viewpager item based on tab click
tabLayout.addOnTabSelectedListener(...);

推荐阅读
地之南_816
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有