2

i working viewpager.i have 4 fragments and add there fragments in viepager.but i want to add fragments dinamically

Here is my adapter

public class MyPagerAdapter extends FragmentPagerAdapter {

private List<Fragment> fragments;

public MyPagerAdapter(FragmentManager fm) {
    super(fm);
    this.fragments = new ArrayList<Fragment>();
    for (int i = 0; i < 10; i++) {
        fragments.add(new FragmentBlue());


    }

}

@Override
public Fragment getItem(int position) {
    return fragments.get(position);
}

@Override
public int getCount() {
    return fragments.size();
}
}

And here is the activity

public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
    ViewPager pager = (ViewPager)findViewById(R.id.myViewPager);
    pager.setAdapter(pageAdapter);
}

}

how i can add fragments dynamically instead of static GetCountSize(). for more information, i want to add 10 fragments in viewpager and each fragments background wast be different.

Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
BekaKK
  • 2,173
  • 6
  • 42
  • 80
  • add new fragments to your List fragments variable and use notifydatasetchanged as in this post http://stackoverflow.com/questions/7263291/viewpager-pageradapter-not-updating-the-view – Illegal Argument Aug 13 '14 at 11:37
  • i update my code please see iy @ Illegal Argument – BekaKK Aug 13 '14 at 13:14
  • Did you find solution on this? Please share if because I'm trying very hard to get the solution on this. – VVB Mar 19 '17 at 15:03

2 Answers2

4

Consider using ViewPager2. By design it allows to modify fragments collection. You can find code sample here.

art
  • 1,222
  • 9
  • 19
0

By using FragmentPagerAdapter we can not achieve infinite pager view functionality.For this I have written my own pager view .Here every time when you swipe the page it will ask for next page /previous page by passing current page as reference.So by writing your own logic in getNextPage(PageView currentPage)/getPreviousPage(PageView currentPage) methods you can return the respective page until it reaches end.if reaches end simply return null in those methods.

Here you can fine that sample project.

Let me know if you face any problem while using it.

Uday Sravan K
  • 1,305
  • 12
  • 18
  • thanks ,but how i can write code to can add button in a first fragment ,edittext in second button and etc.... P.S i updated my code please see it – BekaKK Aug 13 '14 at 13:12