代码片段分享

TabLayout + viewpager + fragment

2020-11-06  本文已影响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));
        }

上一篇下一篇

猜你喜欢

热点阅读