While working with Viewpager which contains multiple Tabs and each tab is a fragment, it is necessary to have an adapter which decides which fragment should be called when user taps on a specific viewpager tab. For this you have to specify a list of fragments which is passed to adapter then this adapter is set to the viewpager. Here is the method to add
and returns
an ArrayList of type Fragment.
public
ArrayList<Fragment> defaultFragmentList(){
ArrayList<Fragment>
fragmentsList
=
new
ArrayList<Fragment>();
fragmentsList
.add(
new
FirstFragment()
);
fragmentsList
.add(
new
SecondFragment()
);
fragmentsList
.add(
new
ThirdFragment());
return
fragmentsList
;
}
After having an arraylist of fragments type we have to pass this list to tabs adapter. Here is the method which takes the fragments arraylist and pass it to adapter.This adapter is set to the viewpager as below:
public
void
populateFragments(ArrayList<Fragment> fragmentsList){
mAdapter =
new
TabsPagerAdapter(
this
, getSupportFragmentManager(),
fragmentsList
);
viewPager.setAdapter(mAdapter);
}
In the onCreate method of the main activity, we call the above methods as:
populateFragments
(
defaultFragmentList());
Now, here is the complete code of
TabsPagerAdapter class.
import
java.util.ArrayList;
import
android.content.Context;
import
android.support.v4.app.Fragment;
import
android.support.v4.app.FragmentManager;
import
android.support.v4.app.FragmentPagerAdapter;
public
class
TabsPagerAdapter
extends
FragmentPagerAdapter {
final
int
TABs=
3
;
Context context;
FragmentManager mFragmentManager;
ArrayList<Fragment> mFragmentsList;
public
TabsPagerAdapter(Context mContext, FragmentManager fm, ArrayList<Fragment> fragmentsList) {
super
(fm);
context=mContext;
mFragmentsList = fragmentsList;
mFragmentManager=fm;
}
@Override
public
Fragment getItem(
int
index) {
Fragment fragment =
null
;
switch
(index) {
case
0
:
fragment = mFragmentsList.get(
0
);
break
;
case
1
:
fragment = mFragmentsList.get(
1
);
break
;
case
2
:
fragment = mFragmentsList.get(
2
);
break
;
}
return
fragment;
}
@Override
public
int
getCount() {
return
TABs;
}
This is one of the simple code.
In case you feel that I need to improve this post/blog Please don't hesitate to comment.
Thank you.
Hello
ReplyDeleteThat is good explanation, but if i want to replace fragment on run time, where do I need to add the code of replacing the fragment for the tab that i want to replace and how do I do that?
thank you