I have a similar problem to the one described here: ViewPager only displaying last fragment, but after attempting the solution there I'm still having the same issue.
I have an app with a TabLayout, which displays 3 fragments. The 3 fragments have the same layout, but the content (text, etc...) of said layouts change depending on the position in the TabLayout. Tab 1 displays one thing, tab 2 another, etc. I do this by passing one class or another to the fragment to be displayed depending on the position passed to getItem() in the pager adapter.
What I'm seeing is that no matter what fragments I attempt to load, my tab layout will always display 3 instances of the same fragment, in this case the last one that gets instantiated. I've stepped through the code and sure enough 3 different fragments get instantiated and returned in getItem() the 3 times its called, but only the one that is returned last is set onto the TabLayout, 3 times.
How can I get it to display the 3 distinct fragments, and not the same one 3 times?
Code used:
@Override
public Fragment getItem(int position) {
MyFragment fragment = new MyFragment();
if (position == 0) {
fragment = MyFragment.newInstance(MyClass1, position); // this gets returned first
} else if (position == 1){
fragment = MyFragment.newInstance(MyClass2, position); // this gets returned second
} else if (position == 2){
fragment = MyFragment.newInstance(MyClass3, position); // this gets returned third and is the only fragment displayed in the 3 tabs
}
return fragment;
}
I believe the issue must be somewhere there, but tell me if I need to share/change other parts of code
EDIT: This is my newInstance() function in my fragment class
public static MarkStudentFragment newInstance(MyClass inputClass, int inputPosition) {
MyFragment fragment = new MyFragment();
dataClass = inputClass;
position = inputPosition;
return fragment;
}
dataClass then gets used to set up the layout of the fragment, etc
public static MarkStudentFragment newInstance(MyClass inputClass, int inputPosition) {
MyFragment fragment = new MyFragment();
dataClass = inputClass;
position = inputPosition
return fragment;
}
If this actually compiles, it is because you have declared dataClass
and position
as static
. So, each time you call newInstance()
, you overwrite the previous dataClass
and position
values. And each of your fragments will use the one-and-only value of dataClass
and position
.
To fix this, get rid of the dataClass
and position
fields, and use the arguments Bundle
. Note that you will need to switch from passing an instance of MyClass
to passing some identifier that will allow the fragment to get the proper data (e.g., an enum
).