Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Add Fragments dynamically to ViewPager
List<Fragment> fragments = buildFragments();
ArrayList<String> categories = {"1", "2", "3", ..., "n"};
mPager = (ViewPager) v.findViewById(;
mPageAdapter = new MyFragmentPageAdapter(this,getSupportFragmentManager(), fragments, categories);
//Add a new Fragment to the list with bundle
Bundle b = new Bundle();
b.putInt("position", i);
String title = "asd";
mPageAdapter.add(MyFragment.class, title, b);
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
public class MyFragmentPageAdapter extends FragmentPagerAdapter {
public static int pos = 0;
private List<Fragment> myFragments;
private ArrayList<String> categories;
private Context context;
public MyFragmentPageAdapter(Context c, FragmentManager fragmentManager, List<Fragment> myFrags, ArrayList<String> cats) {
myFragments = myFrags;
this.categories = cats;
this.context = c;
public Fragment getItem(int position) {
return myFragments.get(position);
public int getCount() {
return myFragments.size();
public CharSequence getPageTitle(int position) {
return categories.get(position);
public static int getPos() {
return pos;
public void add(Class<Fragment> c, String title, Bundle b) {
public static void setPos(int pos) {
MyFragmentPageAdapter.pos = pos;
private List<> buildFragments() {
List<> fragments = new ArrayList<>();
for(int i = 0; i<categories.size(); i++) {
Bundle b = new Bundle();
b.putInt("position", i);
return fragments;
Copy link

ArunCyberenue commented Jan 19, 2017


Copy link

Mukeshkannan-Nplus commented Feb 26, 2017


Copy link

MaheshCapcee commented Mar 30, 2017

can you give me the link to download this project

Copy link

abanoubha commented Jan 24, 2018

Thanks for the great code!

Copy link

rishadb7 commented Jun 5, 2018

Thanx for this code

ping me for complete source code

Copy link

GuyDviri commented Sep 10, 2018

Can its possible to attach fragment to a viewPager after its create with gerFragmentManager()..beingTrans..()..add(simpleFra).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment