TabLayout+ViewPager实现tab和页面联动效果

目录:android.support.design.widget.TabLayout

xml中:




    

    

    

代码中使用:

public class MainActivity extends AppCompatActivity {

    private TabLayout toolbar_tl_tab;
    private ViewPager vp_container;
    private String[] titles = {"标题1", "标题2", "标题3", "标题4"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        toolbar_tl_tab = (TabLayout) findViewById(R.id.toolbar_tl_tab);
        vp_container = (ViewPager) findViewById(R.id.vp_container);
        toolbar_tl_tab.setupWithViewPager(vp_container);
        toolbar_tl_tab.setTabMode(TabLayout.MODE_SCROLLABLE);
        vp_container.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return new PageFragment();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }

            @Override
            public int getCount() {
                return titles.length;
            }
        });
    }

}

碎片:PageFragment

public class PageFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page, null);
        return view;
    }
}

碎片xml:fragment_page.xml




    

注意:

1、模式相关
使用滚动模式,特点是超过屏幕可以滚动显示:

toolbar_tl_tab.setTabMode(TabLayout.MODE_SCROLLABLE);

使用屏幕等分模式,特点是显示tab的宽度是屏幕等分后的宽度:

toolbar_tl_tab.setTabMode(TabLayout.MODE_FIXED);

你可能感兴趣的:(TabLayout+ViewPager实现tab和页面联动效果)