Skip to content

Instantly share code, notes, and snippets.

@rivancic
Created December 15, 2015 17:35
Show Gist options
  • Save rivancic/0f229a6cbdd434c2216c to your computer and use it in GitHub Desktop.
Save rivancic/0f229a6cbdd434c2216c to your computer and use it in GitHub Desktop.
Android Tabs and Swipable Fragments stub
public class TabActivity extends Activity {
TabPageAdapter tabPageAdapter;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
tabPageAdapter = new TabPageAdapter(getSupportFragmentManager(), fragments);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(tabPageAdapter);
final ActionBar actionBar = getSupportActionBar();
// Specify that tabs should be displayed in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
LOG.info("tab " + tab.getPosition() + "selected");
viewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
viewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
getSupportActionBar().setSelectedNavigationItem(position);
}
});
initActionTab(actionBar, "Tab 1", tabListener);
initActionTab(actionBar, "Tab 2", tabListener);
}
private void initActionTab(ActionBar actionBar, String title, ActionBar.TabListener listener) {
actionBar.addTab(
actionBar.newTab()
.setText(title)
.setTabListener(listener));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment