Yes. You can create an adapter with addable fragments.
public class MyAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**Adds a fragment and corresponding title to the list*/
public void addFragment(Fragment f, String title){
mFragmentList.add(f);
mFragmentTitleList.add(title);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
}
And add a viewpager that does not allow sliding between snippets:
public class NonSwipeableViewPager extends ViewPager {
public NonSwipeableViewPager(Context context) {
super(context);
setMyScroller();
}
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setMyScroller();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
//down one is added for smooth scrolling
private void setMyScroller() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
scroller.set(this, new MyScroller(getContext()));
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyScroller extends Scroller {
public MyScroller(Context context) {
super(context, new DecelerateInterpolator());
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
}
}
}
Make setup on activity onCreate:
// Sets up the ViewPager with the sections adapter
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager();
Use this function to setup:
/**Sets up the custom viewpager*/
private void setupViewPager(){
// here we set up our own adapter...
MyAdapter adapter= new MyAdapter(getSupportFragmentManager());
// ...add the fragments we want...
adapter.addFragment(new FragmentOne(), "First");
adapter.addFragment(new FragmentTwo(), "Second");
adapter.addFragment(new FragmentThree(), "Third");
// ...and set up our own adapter on the viewpager
mViewPager.setAdapter(adapter);
}
To add fragments you just have to call the adapter's addFragment ().
If you want, you can put a function in the ViewPager to display the snippet you want. Something like:
public void showFragment(int fragmentIndex){
mViewPager.setCurrentItem(fragmentIndex);
}
Do not forget to use the correct ViewPager in the activity layout.
You can use the source tabs that come in the Android Studio library. You just have to make them interact with ViewPager, and submit the headings accordingly.
I hope it helps.