美文网首页代码片段分享
TabLayout + viewpager + fragment

TabLayout + viewpager + fragment

作者: 花艺荣 | 来源:发表于2020-11-06 14:54 被阅读0次

    用到
    com.google.android.material.tabs.TabLayout
    androidx.viewpager.widget.ViewPager
    FragmentPagerAdapter

    问题1,当数据源变化时去切换,未重置页面。
    解决:

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
                }
    
                @Override
                public void onPageSelected(int position) {
    
                        Fragment fragment =  (Fragment)viewPager.getAdapter().instantiateItem(viewPager, position);
                        fragment.refresh(); 
                }
    
                @Override
                public void onPageScrollStateChanged(int state) {
    
                }
            });
    

    问题2,包含两个tab页,两个Tab title样式不一样
    解决:

    TabLayout.Tab tab = tabs.getTabAt(0);
            View view = tab.getCustomView();
            if (null == view) {
                tab.setCustomView(R.layout.trans_cus_tab_layout);
                ((TextView)tab.getCustomView().findViewWithTag("tabtitle")).setText(sectionsPagerAdapter.getPageTitle(0));
            }
            TabLayout.Tab tab2 = tabs.getTabAt(1);
            View view2 = tab2.getCustomView();
            if (null == view2) {
                tab2.setCustomView(R.layout.trans_cus_tab_layout2);
                ((TextView)tab2.getCustomView().findViewWithTag("tabtitle")).setText(sectionsPagerAdapter.getPageTitle(1));
            }
    
    

    相关文章

      网友评论

        本文标题:TabLayout + viewpager + fragment

        本文链接:https://www.haomeiwen.com/subject/klutbktx.html