Android Design Support Library -- TabLayout, androidtablayout
TabLayout -- tab layout. Switching views through tabs is not a new concept in material design. Tabs can be fixed or scrolling as follows:
You can use the addTab method to dynamically add tabs:
tabLayout.addTab(tabLayout.newTab().setText("tab1"));
The setupWithViewPager () method can be used to associate with Viewpager. This method updates ViewPager for the selected tab event, and changes the page of ViewPager to update the Selected tab status. Note that if you associate with Viewpager, you can use the getPageTitle () method of PagerAdapter to create a tab.
private void setupViewPager(ViewPager viewPager) { Adapter adapter = new Adapter(getSupportFragmentManager()); adapter.addFragment(new CheeseListFragment(), "Category 1"); adapter.addFragment(new CheeseListFragment(), "Category 2"); adapter.addFragment(new CheeseListFragment(), "Category 3"); viewPager.setAdapter(adapter); }
static class Adapter extends FragmentPagerAdapter { private final List<Fragment> mFragments = new ArrayList<>(); private final List<String> mFragmentTitles = new ArrayList<>(); public Adapter(FragmentManager fm) { super(fm); } public void addFragment(Fragment fragment, String title) { mFragments.add(fragment); mFragmentTitles.add(title); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitles.get(position); } }
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); if (viewPager != null) { setupViewPager(viewPager); } TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);tabLayout.setupWithViewPager(viewPager);
Declaration in xml
<android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" />
In addition, when the number of tabs is too large, you can use tabLayout. setTabMode (TabLayout. MODE_SCROLLABLE) to horizontally scroll tabs.