private TabLayout mTabTl;
private ViewPager mContentVp;
private List tabIndicators;
private List tabFragments;
private ContentPagerAdapter contentAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_layout);
mTabTl = (TabLayout) findViewById(R.id.tl_tab);
mContentVp = (ViewPager) findViewById(R.id.vp_content);
initContent();
initTab();
}
private void initTab(){
mTabTl.setTabMode(TabLayout.MODE_SCROLLABLE);
mTabTl.setTabTextColors(ContextCompat.getColor(this, R.color.gray), ContextCompat.getColor(this, R.color.white));
mTabTl.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.white));
ViewCompat.setElevation(mTabTl, 10);
mTabTl.setupWithViewPager(mContentVp);
}
private void initContent(){
tabIndicators = new ArrayList<>();
for (int i = 0; i < 3; i++) {
tabIndicators.add("Tab " + i);
}
tabFragments = new ArrayList<>();
for (String s : tabIndicators) {
tabFragments.add(TabContentFragment.newInstance(s));
}
contentAdapter = new ContentPagerAdapter(getSupportFragmentManager());
mContentVp.setAdapter(contentAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tab_layout, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.tab_add:
tabIndicators.add("Tab " + tabIndicators.size());
tabFragments.add(TabContentFragment.newInstance(tabIndicators.get(tabIndicators.size()-1)));
contentAdapter.notifyDataSetChanged();
return true;
case R.id.tab_mode_fixed:
mTabTl.setTabMode(TabLayout.MODE_FIXED);
return true;
case R.id.tab_mode_scrollable:
mTabTl.setTabMode(TabLayout.MODE_SCROLLABLE);
break;
}
return super.onOptionsItemSelected(item);
}
class ContentPagerAdapter extends FragmentPagerAdapter{
public ContentPagerAdapter(FragmentManager fm) {