Reputation: 269
I've created a ViewPager with 8 fragments that use the same xml layout. However, I want different fragments to use different content. I need to get the ID of whatever fragment it is so I can load specific content onto that fragment.
I've tried
extras.putInt(Globals.KEY_CATEGORY_POSITION, position);
fragment.setArguments(extras);
in the getItem(int position) method on the FragmentPagerAdapter.
Then, I get the position of the fragment in the Fragment class. When I do this, I go from 0 to 7 when I print out the position of each fragment but then all of them increment to 7 so they all become the same fragment.
Is there any other way to get the ID for each fragment?
Upvotes: 2
Views: 7472
Reputation: 14744
Here is a quite nice example:
When you are creating fragment:
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
And then in fragment:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
Upvotes: 3
Reputation: 6380
Throw this inside your FragmentPagerAdapter :)
public Fragment getActiveFragment(ViewPager container, int position) {
String name = makeFragmentName(container.getId(), position);
return mFragmentManager.findFragmentByTag(name);
}
private static String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
Upvotes: 0