I have an Activity with a traditionnal viewpager component. This viewpager contains MainFragment class (it's a standard fragment). This is the layout of this fragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</FrameLayout>
Ps: I need to use this framelayout because I can switch with 2 fragments inside according an user data.
In this MainFragment I want to show a specific fragment according an user data:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final Bundle bundle = getArguments();
int mydata = bundle.getInt(BUNDLE_KEY_MY_DATA);
if (mydata == 1)
addFragment(Fragment1.newInstance(), Fragment1.TAG);
else if (mydata == 2)
addFragment(Fragment2.newInstance(), Fragment2.TAG);
}
My addFragment method:
protected void addFragment(@NonNull Fragment fragment,
@NonNull String fragmentTag) {
getFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragment, fragmentTag)
.disallowAddToBackStack()
.commit();
}
But there is a strange behavior during execution (no crash!). For example in my tab (associated with the viewpager) there are these elements: "1" "2" "3" "4" "5" "6" "7"
So the default position is on element "4"; it works perfectly. Now if I swipe for example to "3", the Fragment1 (or Fragment2 doesn't matter) doesn't appear. To show it, I must to swipe again (so to "2"), then come back to "3" and the fragment appears correctly.
Thanks for your help guys!
Use
Fragment.getChildFragmentManager()
in youraddFragment()
.