Skip to content

Instantly share code, notes, and snippets.

@BenoitDuffez
Last active December 27, 2015 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenoitDuffez/7355253 to your computer and use it in GitHub Desktop.
Save BenoitDuffez/7355253 to your computer and use it in GitHub Desktop.
public class ViewPagerFragment extends Fragment {
private MyTabsAdapter mAdapter;
private static final int NB_TABS = 2; // to change with what you need
private static final String[] TAB_TITLES = new String[NB_TABS];
public static ViewPagerFragment newInstance(final Bundle args) {
final ViewPagerFragment f = new ViewPagerFragment();
f.setArguments(args);
return f;
}
private static class MyTabsAdapter extends FragmentPagerAdapter {
Fragment[] mFragments = new Fragment[NB_TABS];
Bundle args;
public MyTabsAdapter(final FragmentManager fm, final Bundle args) {
super(fm);
this.args = args;
Bundle hack = new Bundle();
try {
for (int i = 0; i < mFragments.length; i++) {
hack.putInt("hack", i);
mFragments[i] = fm.getFragment(hack, "hack");
}
} catch (Exception e) {
// No need to fail here
}
}
@Override
public int getCount() {
return NB_TABS;
}
@Override
public CharSequence getPageTitle(final int position) {
return TAB_TITLES[position].toUpperCase(Locale.getDefault());
}
/**
* @return The {@code Fragment} at that position
*/
public Fragment getFragment(final int position) {
return mFragments[position];
}
@Override
public Fragment getItem(final int position) {
if (position == 0) {
mFragments[position] = YourFirstFragment.newInstance(args);
} else {
mFragments[position] = YourSecondFragment.newInstance(args);
}
// to change with your fragments
return mFragments[position];
}
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.frag_viewpager, container, false);
int i = 0;
TAB_TITLES[i++] = getString(R.string.issue_overview_title);
TAB_TITLES[i++] = getString(R.string.issue_journal_title);
// set the titles here
final Bundle args = new Bundle();
if (getArguments() != null) {
args.putAll(getArguments());
}
if (savedInstanceState == null) {
// create your stuff when the fragments are created from scratch
} else {
// re-use anything from the previous instance
}
mAdapter = new MyTabsAdapter(getChildFragmentManager(), args);
final ViewPager pager = (ViewPager) v.findViewById(R.id.issue_pager);
pager.setAdapter(mAdapter);
return v;
}
@Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment