So I am working on a project I want to run on legacy Android devices so I am using the compatibility library. I am using an interface similar to NewsReader, only instead of the two fragments being in the Activity, they are embedded in another Fragment, which is embedded in a ViewPagger.
For simplicity we will use these terms...
Activity -> ViewPager -> ContainerFragment->Fragment1
->Fragment2
In ContainerFragment I am trying to replace out fragment 1 with fragment 2 if it is a phone so I tried the following code in ContainerFragment...
import android.support.v4.app.FragmentTransaction;
...
public void onBarSelected(Integer index) {
selectedBarIndex = index;
if (isDualPane) {
// display it on the article fragment
mBarEditFragment.displayBar(index);
}
else {
// use separate activity
FragmentActivity activity = (FragmentActivity)getActivity();
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
ft.replace(R.id.bar_container, new BarEditFragment(),R.id.bar_edit);
}
}
But I get the following compile error
Type mismatch: cannot convert from android.app.FragmentTransaction
to android.support.v4.app.FragmentTransaction
I double checked and the activity does extend the compatibility FragmentActivity.
UPDATE
Tried to change to...
and got....
MainActivity activity = (MainActivity)getActivity();
Object test = activity.getFragmentManager().beginTransaction();
FragmentTransaction ft = (FragmentTransaction)test;
ft.replace(R.id.bar_container, new BarEditFragment());
And I got...
java.lang.ClassCastException: android.app.BackStackRecord cannot be cast to android.support.v4.app.FragmentTransaction
Any ideas?
ANSWER:
I figured out my problem The issue is you shouldn't get the Fragment manager from the Activity and should get it from the fragment instead.
This works....
public void onBarSelected(Integer index) {
selectedBarIndex = index;
if (isDualPane) {
// display it on the article fragment
//mBarEditFragment.displayBar(index);
}
else {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.bar_container, new BarEditFragment());
ft.commit();
}
}