Java – getting fragmenttransaction from activity when using compatibility

So I'm developing a project that I want to run on traditional Android devices, so I use the compatibility library I use an interface similar to newsreader, but instead of two fragments in activity, they are embedded in another fragment embedded in viewpagger

For simplicity, we will use these terms

Activity -> ViewPager -> ContainerFragment->Fragment1
                                          ->Fragment2

In containerfragment, I tried to replace fragment 1 with fragment 2 if it was 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 got the following compilation errors

Type mismatch: cannot convert from android.app.FragmentTransaction 
 to android.support.v4.app.FragmentTransaction

I checked carefully that the activity does extend the compatibility fragmentactivity

UPDATE

Try to change to

Get

MainActivity activity = (MainActivity)getActivity();
Object test = activity.getFragmentManager().beginTransaction();
FragmentTransaction ft = (FragmentTransaction)test;
ft.replace(R.id.bar_container,new BarEditFragment());

I got

java.lang.ClassCastException: android.app.BackStackRecord cannot be cast to android.support.v4.app.FragmentTransaction

Any ideas?

answer:

I came up with my problem. The problem is that you should not get the fragment manager from the activity, but get it from the fragment

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();
    }

}

Solution

Faced with the same problem, solved the use

thank you

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>