It was tricky to write a title for this. What I currently do, is to reuse one Fragment class to create a multitude of ListFragments in a ViewPager.
The layout of the ListFragments are all the same so having just one layout and one Fragment as a base seems like a sound choice.
However, I’d like to be able to access each Fragment’s views, in order to set some per-Fragment values, such as a title, a name and whatnot. I have an issue with this and it’s the fact that whenever I try to access a TextView by overriding a Fragment’s onViewCreated-method, it seems to me that the only Fragment getting updated is the first one in the chain.
Now, what I do to instantiate and connect the Fragments is this:
private void initPager() {
mFragments = new Vector<Fragment>();
int[] listIds = 3;
for(int i = 0; i < listIds.length; i++) {
Fragment fragment = new ListsFragment(listIds[i]);
mFragments.add(fragment);
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
for(int i = 0; i < mFragments.size(); i++) {
fragmentTransaction.add(R.id.viewpager, mFragments.get(i));
}
fragmentTransaction.commit();
mPagerAdapter = new ListsPagerAdapter(fragmentManager, mFragments);
mPager = (ViewPager) super.findViewById(R.id.viewpager);
mPager.setAdapter(mPagerAdapter);
}
The Fragment onViewCreated() code is this:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textListTitle = (TextView) getActivity().findViewById(R.id.text_list_title);
String title = "test";
textListTitle.setText(listTitle);
}
When looking at logs I see that each Fragment is instantiated separatly, going through the lifecycle of each in succession. However, the only Fragment getting the “test”-string is the first one.
What am I missing?
You should be instantiating your
Fragments in aFragmentPagerAdapterof some sort.