ViewPager

<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/toolbar" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/> <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_below="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> public class PagerAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; public PagerAdapter(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { MyConstant constant = MyConstant.getInstance(); switch (position) { case 0: return new FragmentGridBook(constant.ONLINE_DATA); case 1: return new FragmentGridBook(constant.OFFLINE_DATA); case 2: return new FragmentGridBook(constant.FAVORITE_DATA); default: return null; } } @Override public CharSequence getPageTitle(int position) { MyConstant constant = MyConstant.getInstance(); switch (position) { case 0: return "Sách Online"; case 1: return "Sách Offline"; case 2: return "Sách yêu thích"; default: return "Tab"; } } @Override public int getCount() { return mNumOfTabs; } } //-------------------------------------------------------------------------------------------------------- private void initViewPager() { TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText("Tab 1")); tabLayout.addTab(tabLayout.newTab().setText("Tab 2")); tabLayout.addTab(tabLayout.newTab().setText("Tab 3")); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); _pagerAdapter = new PagerAdapter(getSupportFragmentManager(), 3); // Set up the ViewPager with the sections adapter. _viewPager = (ViewPager) findViewById(R.id.container); _viewPager.setAdapter(_pagerAdapter); _viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { _viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.