Skip to content Skip to sidebar Skip to footer

Working With Viewpager And Fragments

I am a beginner Android developer. I am trying to get my head around the ViewPager. Before I was trying to work with this example: http://mobile.tutsplus.com/tutorials/android/andr

Solution 1:

Declare this inside your MyFragmentPagerAdapter:

private Fragment[] fragments = new Fragment[] { newFragment1(),Fragment2(),Fragment3(),Fragment4(),Fragment5()};

then implement getItem method like this:

@Overridepublic Fragment getItem(int index) {  

              return fragments[index];
         } 

and for each fragment have it is own class and layout:

publicclassFragment1extendsFragment { 
   //your code here
}

Solution 2:

Assuming you know how to create fragments themselves, just do something like this to get them into your view pager:

@Overridepublic Fragment getItem(int page) {
            switch (page) {
                case0: returnnewMyFirstFragment();
                case1: returnnewMySecondFragment();
                case2: returnnewMyThirdFragment();
                //and so on....
            }
            returnnull;
        }

        @OverridepublicintgetCount() {
            return [the count of total fragments];
        }

instead of this:

@Overridepublic Fragment getItem(int index) {  
          return PageFragment.newInstance("My Message " + index);
     }

Solution 3:

I modified the answer from hambonious a bit:

Declare this inside your MyFragmentPagerAdapter :

private SparseArray<Fragment> fragments = new SparseArray<Fragment>();

then implement getItem method like this:

@Overridepublic Fragment getItem(int index) {
     if(fragments != null && fragments.size() >= index)
        return fragments.get(i);
     elsereturnnull;
 }

You also have to override getSize()

 @Override
 publicintgetCount() {
    return fragments.size();
 }

Then you can dynamic add and remove fragments from it.

Post a Comment for "Working With Viewpager And Fragments"